在python2.7中,使用socket编程将服务器接收到的消息发送到多个客户端

2024-03-28 18:57:08 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我为客户机和服务器创建了一个socket程序作为基本的聊天。我这样做是为了让服务器接受多个带有线程的客户机,所以这不是问题所在。我在向每个连接到服务器的客户端发送消息时遇到问题。我不想让服务器发送它创建的消息,而是让client1通过服务器向client2发送消息。由于某些原因,它只会将其发送回client1。在

例如,client1将打招呼,服务器将向client1发送相同的消息,但不向{}发送任何消息。我通过确保客户机没有收到它自己的消息,但是client2仍然没有从client1接收消息来稍微修复了这个问题。在

任何帮助都将不胜感激。在

我尝试了多次改变,但似乎没有任何效果。您可以查看我的代码以了解我是如何做事情的,但如果有任何问题,请询问。在

另外,有一个问题,有人问过类似的问题,我想它会给我一个答案,但回答停止了,而且从来没有给出完整的解决方案,所以请不要让我只提到这个问题。位于这里:Python 3: Socket server send to multiple clients with sendto() function。在

代码如下:

客户: 导入套接字 导入系统 导入线程

#Create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Enter username to identify self to others
name = raw_input("Enter username: ") + ": "

#Connect socket to ip and port
host = socket.gethostname()
#host = '192.168.1.10'
server_address = (host, 4441)
sock.connect(server_address)

#function waiting to receive and print a message
def receive(nothing):

    while True:

        data = sock.recv(1024)
        if message != data:
            print data

# Send messages
while True:
    #arbitrary variable allowing us to have a thread
    nothing = (0, 1)

    message = name + raw_input("> ")
    sock.sendall(message)

    #thread to receive a message
    thread.start_new_thread(receive, (nothing,))

服务器:

^{pr2}$

如果可以的话,请帮帮我!在

编辑:

我能在一定程度上修复它。它仍然是一个小推车,但我现在可以发送信息来回。我需要指定连接套接字以及地址。以下是更新后的代码:

服务器

import socket
import sys
import thread

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
host = socket.gethostname()
server_address = (host, 4441)
sock.bind(server_address)

#Listen for incoming connections
sock.listen(5)
print "Waiting for connection..."

#Variable for the number of connections
numbOfConn = 0

#Name of list used for connections
addressList = []
connectionList = []

#Function that continuosly searches for connections
def clients(connectionList, addressList):

    while True:
        for j in range(0,numbOfConn):
            message = connectionList[j].recv(1024)
            print message

            #for loop to send message to each
            for i in range(0,numbOfConn):
                connectionList[i].sendto(message, addressList[i])

    connection.close()

while True:
    #accept a connection
    connection, address = sock.accept()
    print 'Got connection from', address

    numbOfConn += 1
    addressList.append((address))
    connectionList.append((connection))

    #Thread that calls the function: clients and stores them in a tuple called connection
    thread.start_new_thread(clients, (connectionList, addressList))


sock.close()

Tags: to服务器host消息messageforserveraddress