gpt4 book ai didi

python - 套接字编程问题 - Python

转载 作者:行者123 更新时间:2023-11-28 17:53:41 27 4
gpt4 key购买 nike

好吧,我花了大约三个小时在 Python 中摆弄套接字编程,试图制作一个简单的聊天程序。我已经让客户端向服务器发送文本,然后从客户端向它自己重复消息。但是,我希望将消息发送到服务器,然后服务器而不是客户端将其重新发送给所有连接的客户端。我在执行此操作时遇到问题。到目前为止,这是我的代码:

服务器端代码:

import SocketServer

def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "%s wrote:" % self.client_address[0]
print data
socket.sendto(data.upper(), self.client_address)


if __name__ == "__main__":
HOST, PORT = "localhost", 25555
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
server.serve_forever()

客户端代码:

import socket
import sys
global HOST
global PORT
HOST, PORT = "localhost", 25555
while 1 > 0:
data = raw_input(">".join(sys.argv[1:]))

# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)

print "Sent: %s" % data
print "Received: %s" % received

最佳答案

现在您的应用正在为每个客户端连接实例化 MyUDPHandler 类。打开连接后,您需要将该实例存储到静态数组或队列中。然后,当调用 handle() 时,它可以遍历所有这些套接字并将数据副本发送到每个套接字。

我会查看 python 文档;它基本上可以满足您的需求:http://docs.python.org/library/socketserver.html#asynchronous-mixins

我想从那个例子中改变什么(不要只是把它丢进去;它可能有明显的错误!):

handlerList = []class ...    def handle(self):        handlerList.append(self)        while (1):          data = self.request.recv(1024)          if (not data):            break          cur_thread = threading.currentThread()          response = "%s: %s" % (cur_thread.getName(), data)          for x in handlerList:            x.request.send(response)        psudo_code_remove_self_from_handlerList()

关于python - 套接字编程问题 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com