python套接字网络中的多个消息交换

时间:2018-01-10 07:03:03

标签: python multithreading python-3.x sockets networking

这是我在新闻选项上询问输入基础的简单程序:

from newsapi.articles import Articles
import sys


a=Articles('cff9541f3b5a4558957e63ea59b3743b')
#key is working you can use it for testing 

def news_choice():
    options = ['news', 'jokes', 'life_style']
    print(options)
    print('\n')
    print('------------------------------')
    inpu = input("what do you want? ")             #input_1
    if inpu == 'news':
        print([k for i in a.get_by_popular(source='techcrunch')['articles'] for k in i])
        print('\n')
        print('------------------------------')

        inpu = input(
            'Which option would you like to select : description , author , url , urlToImage , title, publishedAt ')   #input_2
        print([i[inpu] for i in a.get_by_popular(source='techcrunch')['articles']])

        inpu = input("would you like to quit ? yes | No ")  #input_3
        if inpu == 'yes':
            sys.exit()
        else:
            news_choice()
news_choice()

输出是:

['news', 'jokes', 'life_style']


------------------------------
what do you want? news
['urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description']


------------------------------
Which option would you like to select : description , author , url , urlToImage , title, publishedAt title
['Huawei’s Richard Yu is really pissed at US\xa0carriers', 'H-1B visa extensions for workers waiting on green cards are safe for\xa0now', 'Kodak announces ICO, stock jumps\xa044%', 'Razer moves into wireless power, debuts HyperFlux mouse and\xa0pad']
would you like to quit ? yes | No yes

Process finished with exit code 0

现在我想让我的脚本成为服务器,任何人都可以通过telnet连接到我的脚本,所以我有这个服务器和客户端脚本:

import socket
import threading
import last_commit
class ThreadedServer(object):
    dict_cache={}



    def __init__(self, host, port):
        self.host = host
        self.port = port


        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):

        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            print("client post is {}".format(address[1]))
            self.dict_cache['client']=address[1]
            print(self.dict_cache)
            client.settimeout(60)
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1000000
        while True:
            try:
                data = client.recv(size)
                if data:
                    da_1= str(data,'utf-8')


                    # Set the response to echo back the recieved data

                    reply=last_commit.chat_bot_reply(da_1).encode()

                    client.send(reply)
                    tmp_dict = {"customer": da_1, "bot": reply}
                    if address[0] not in self.dict_cache:
                        self.dict_cache[address[0]]=[tmp_dict]
                    else:
                        self.dict_cache[address[0]].append(tmp_dict)

                    print(self.dict_cache)



                else:
                    raise Exception('Client disconnected')
            except:
                client.close()
                return False

while True:
    port_num = input("Port? ")
    try:
        port_num = int(port_num)
        break
    except ValueError:
        pass

ThreadedServer('', port_num).listen()

现在我修改了上面的脚本,使我的脚本成为服务器,如下所示:

import socket
import threading
from newsapi.articles import Articles
import sys
class ThreadedServer(object):
    dict_cache={}



    def __init__(self, host, port):
        self.host = host
        self.port = port


        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind((self.host, self.port))

    def listen(self):

        self.sock.listen(5)
        while True:
            client, address = self.sock.accept()
            print("client post is {}".format(address[1]))
            self.dict_cache['client']=address[1]
            print(self.dict_cache)
            client.settimeout(60)
            threading.Thread(target = self.listenToClient,args = (client,address)).start()

    def listenToClient(self, client, address):
        size = 1000000
        client.send('Hi,Welcome to Apolo fun'.encode())
        while True:
            try:

                data = client.recv(size)
                if data:
                    da_1= str(data,'utf-8')




                    a = Articles('cff9541f3b5a4558957e63ea59b3743b')

                    def news_choice():
                        options = ['news', 'jokes', 'life_style']
                        client.send(b'working')
                        client.send(options.encode())
                        client.send(b'\n')
                        client.send(b'------------------------------')
                        data_1 = client.recv(size)
                        if data_1 == 'news':
                            client.send([k for i in a.get_by_popular(source='techcrunch')['articles'] for k in i].encode())
                            client.send('\n'.encode())
                            client.send('------------------------------'.encode())
                            data_2 = client.recv(size)


                            print([i[data_2] for i in a.get_by_popular(source='techcrunch')['articles']])

                            data_3 = client.recv(size)
                            if data_3 == 'yes':
                                sys.exit()
                            else:
                                news_choice()

                    news_choice()




                else:
                    raise Exception('Client disconnected')
            except:
                client.close()
                return False

while True:
    port_num = input("Port? ")
    try:
        port_num = int(port_num)
        break
    except ValueError:
        pass

ThreadedServer('', port_num).listen()

我的客户端脚本是:

import socket

import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = int(input("Server port? "))
sock.connect((host,port))
while True:
    print("response: ", sock.recv(1024))
    data = input("message: ")
    sock.send(data.encode())
    print("response: ", sock.recv(1024))
    print("response: ", sock.recv(1023))
    print("response: ", sock.recv(1023))
    print("response: ", sock.recv(1023))

现在您可以看到我的原始脚本中有三个输入,我的主要困惑是服务器客户端正在处理消息 - >回应 - >消息 - >响应senerio所以,如果我收到来自客户端的任何消息我将如何确定此消息是针对哪个输入并且它可以打破功能范围,例如,如果我需要input_2在news_api输出的范围内,现在如果我从任何消息来自客户端如何将输出放在input_2的位置。

如果它令人困惑然后我的结论是我希望通过服务器客户端的预期输出是这样的,我如何将我的原始程序转换为服务器并让任何人通过该客户端脚本连接

['news', 'jokes', 'life_style']


------------------------------
what do you want? news
['urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description', 'urlToImage', 'title', 'publishedAt', 'author', 'url', 'description']


------------------------------
Which option would you like to select : description , author , url , urlToImage , title, publishedAt title
['Huawei’s Richard Yu is really pissed at US\xa0carriers', 'H-1B visa extensions for workers waiting on green cards are safe for\xa0now', 'Kodak announces ICO, stock jumps\xa044%', 'Razer moves into wireless power, debuts HyperFlux mouse and\xa0pad']
would you like to quit ? yes | No yes

0 个答案:

没有答案
相关问题