简体   繁体   English

套接字编程问题 - Python

[英]Socket Programming Issue - Python

Alright, I've spent about three hours fiddling with socket programming in Python trying to make a simple chat program. 好吧,我花了大约三个小时摆弄Python中的套接字编程,试图制作一个简单的聊天程序。 I've gotten the client to send text to the server and then, from then client, it repeats the message to it's self. 我已经让客户端将文本发送到服务器,然后,从那时客户端,它重复消息给它自己。 However, I want the message to be sent to the server and then the server, not the client, re-send it to all client's connected. 但是,我希望将消息发送到服务器,然后服务器而不是客户端将其重新发送到所有连接的客户端。 I'm having issues doing this. 我这样做有问题。 This is my code so far: 到目前为止这是我的代码:

Server Side Code: 服务器端代码:

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()

Client Side Code: 客户端代码:

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

Right now your app is instantiating the MyUDPHandler class for each client connection. 现在,您的应用程序正在为每个客户端连接实例化MyUDPHandler类。 When the connection is opened you need to store that instance to a static array or queue. 打开连接时,您需要将该实例存储到静态数组或队列。 Then when the handle() call is made it can loop through all those sockets and send a copy of the data to each of them. 然后,当调用handle()时,它可以循环遍历所有这些套接字并将数据的副本发送给每个套接字。

I'd checkout the python documentation; 我要查看python文档; it basically does what your looking to: http://docs.python.org/library/socketserver.html#asynchronous-mixins 它基本上做你想要的: http//docs.python.org/library/socketserver.html#asynchronous-mixins

And what I'd change from that example (Don't just drop this in; it probably has glaring bugs!): 我从那个例子中改变了什么(不要只是放弃它;它可能有明显的错误!):

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()

Would you like to play with a server that echos packets to all sockets but the original source of the data? 您是否希望使用服务器将数据包发送到所有套接字但是原始数据源?

import socket, select

def main():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('', 8989))
    server.listen(5)
    sockets = [server]
    while True:
        for sender in select.select(sockets, [], [])[0]:
            if sender is server:
                sockets.append(server.accept()[0])
            else:
                try:
                    message = sender.recv(4096)
                except socket.error:
                    message = None
                if message:
                    for receiver in sockets:
                        if receiver not in (server, sender):
                            receiver.sendall(message)
                else:
                    sender.shutdown(socket.SHUT_RDWR)
                    sender.close()
                    sockets.remove(sender)

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM