使用python中的套接字转发和打印来自多个客户端的消息

时间:2017-06-09 16:39:57

标签: python python-3.x sockets client-server

我知道有很多帖子的标题与此类似。他们中的大多数人没有答案或只是回答如何回应一个客户而不是多个。我已经用这段代码抨击了我的脑袋。我确信接收连接并将它们添加到列表中是有效的。我的问题是当我尝试从客户端屏幕打印消息时。一个客户端工作正常,你可以在屏幕上显示他的消息,问题来自多个客户端。当第二个客户端连接时,您无法在服务器端看到他的消息,在第一个客户端发送一些消息后,将显示从第二个客户端发送的消息。所以我确信邮件正在收到,问题在于打印。

服务器脚本:     import socket,sys     来自线程导入线程

prevcon=0
buffsize=1024
connections=[]
addreses=[]
try:
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

except socket.error as e:
   print ("Failed to create a socket")
   print (e)


host="192.168.0.103"#raw_input("Enter Target host here: ")
port=12345#raw_input("Enter Target port here: ")

try:
    s.bind((host,int(port)))

except socket.error as e:
    print ("Failed to Connect")
    print (e)

s.listen(5)
s.setsockopt( socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1 )


def listen_connections():
        while True:
            #print ("waiting for connection")
            client_sock, addr = s.accept()
            connections.append(client_sock)
            addreses.append(addr)
            print ("client connected from: ",addr)


def print_messages():
    while True:
        for i in range(0,len(connections)):
            try:
                data=connections[i].recv(buffsize)
            except socket.error:
                print ("User Disconnected from: ",connections[i])
                connections[i].close()
                del connections[i]
                del addreses[i]
                continue
            print (data.decode("utf-8"))
            print (connections)
            #send_message(data,i)

    s.close()

def send_message(data,pos):
        for connection in connections:
            if connection!=connections[pos]:
                connection.send(data)



if __name__=="__main__":
    thread1=Thread(target=listen_connections)
    thread2=Thread(target=print_messages)
    thread1.daemon=True
    thread2.daemon=True
    thread1.start()
    thread2.start()

客户端脚本:

    import socket,sys
from threading import Thread

try:
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

except socket.error as e:
    print ("Failed to create a socket")
    print e

host="192.168.0.103"#raw_input("Enter Target host here: ")
port=12345#raw_input("Enter Target port here: ")

try:
    s.connect((host,int(port)))

except socket.error as e:
    print "Error Connecting"
    print e

print ("Connected to host: %s and port: %s" %(host,port))

def leer():
    while True:
        data=s.recv(1024)
        print data.decode("utf-8")


def send():
    while True:
        payload=raw_input("Enter here text to send: ")
        s.send(payload)

if __name__=="__main__":
    t1=Thread(target=leer)
    t2=Thread(target=send)
    t1.daemon=True
    t2.daemon=True
    t1.start()
    t2.start()

0 个答案:

没有答案