如何使用python(socket)在客户端之间发送和接收消息?

时间:2019-04-03 13:53:12

标签: python sockets server client

我们正在使用python(socket)开发一个项目“ ByZantine Generals Problem”,我们设法在服务器与两个客户端(client1,client2)之间创建成功的连接。但是我们不知道如何在两个客户端之间建立连接,有帮助吗?

链接模型项目问题:https://upload.wikimedia.org/wikipedia/commons/thumb/8/81/4generalestenientetraidor.svg/400px-4generalestenientetraidor.svg.png

Server.py

import socket


host = '192.168.43.209'  # Standard loopback interface address 
(localhost)
port = 65432        # Port to listen on (non-privileged ports are > 1023)

serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serv.bind((host, port))
serv.listen(5)

while True:
    conn, addr = serv.accept()
    conn.send(b"Attack ")
    data = conn.recv(4096)
    if not data: break
    print (data)

client1.py

import socket

host = '192.168.43.209'  # Standard loopback interface address         
(localhost)
port = 65432        # Port to listen on (non-privileged ports are > 1023)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))



from_server = client.recv(4096)
print (from_server)
client.send(b"I am client 1 :  ")

client2.py

import socket

host = '192.168.43.209'  # Standard loopback interface address 
(localhost)
port = 65432        # Port to listen on (non-privileged ports are > 1023)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))



from_server = client.recv(4096)
print (from_server)
client.send(b"I am client 2 :  ")

1 个答案:

答案 0 :(得分:0)

您可以使用以下方法通过服务器进行客户端到客户端的通信。注意:目前尚未对此进行测试,因为我不在可以运行此命令的计算机上:

此代码的核心来自此答案,该答案说明了如何向所有客户端发送消息:https://stackoverflow.com/a/27139338/8150685

我为list使用了clients,但是您可能会发现使用dictionary更容易。

clients = [] # The clients we have connected to
clients_lock = threading.Lock()

def listener(client, address):
    print "Accepted connection from: ", address
    with clients_lock:
        clients.append(client) # Add a client to our list
    try:    
        while True:
            data = client.recv(1024)
            if not data:
                break
            else:
                print repr(data)
                # Here you need to read your data
                # and figure out who you want to send it to
                client_to_send_to = 1 # Send this data to client 1
                with clients_lock:
                    if client_to_send_to < len(clients):
                        clients[client_to_send_to].sendall(data)
    finally:
        with clients_lock:
            clients.remove(client)
            client.close()