线程 - 如何使用套接字模块同时接收和回复?

时间:2014-03-01 17:01:20

标签: python multithreading sockets while-loop messages

我正在尝试创建一个简单的LAN即时消息,其中许多客户端连接到服务器,服务器回复并可以看到客户端说的内容。我试过但是我使用线程模块缺乏知识限制了我。但是,目前服务器只收到一条消息,必须回复才能获得下一条消息。我试图让它成为服务器可以立即看到它收到的所有消息,并可以随时回复。怎么样? 服务器代码:

from threading import *
import socket

s = socket.socket()         
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)

def getMainThread():
    for thread in enumerate(): # Imported from threading
        if thread.name == 'MainThread':
            return thread
        if thread.name == 'Thread':
            return thread
    return None

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.socket = socket
        self.address = address
        self.start() # Initated the thread, this calls run()

    def reply(self):
        reply = getThread()
        while reply and reply.isAlive():
            sent = input("Enter Message: ")
            self.socket.send(bytes(sent, 'UTF-8'))

    def run(self):
        main = getMainThread()
        while main and main.isAlive():
            message = self.socket.recv(8192).decode('utf-8')
            self.socket.send(b"Got your message.. send another one!")
            print('Someone:',message)
            sent = input("Enter Message: ")
            self.socket.send(bytes(sent, 'UTF-8'))



            self.socket.close()

    while True:
       c, addr = s.accept()
       client(c, addr)

客户代码:

import socket
host = socket.gethostbyname(socket.gethostname())
print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))

#host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))

sock = socket.socket()
try:
    sock.connect((host, 1337))
    while True:
        message = input("Enter Message: ")
        if message == 'quit':
            break
        sock.send(bytes(message, 'UTF-8'))
        recieved = sock.recv(8192).decode('utf-8')
        print('Server responded with:', recieved)
except socket.error:
     print ("Host is unreachable")

sock.close()

此外,是否可以使用线程,以便2个while语句可以同时运行?如果是这样,有人可以给我一个例子吗?

提升这个尝试并得到答案。任何人吗?

0 个答案:

没有答案