Socket Problem - Python

Well, I spent about three hours playing with socket programming in Python, trying to create a simple chat program. I got a client to send text to the server, and then, from that moment, it repeats the message itself. However, I want the message to be sent to the server, and then the server, and not the client, to resend it to all the connected client. I have problems with this. This is my code:

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 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
+3
source share
2 answers

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

, - , ?

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

Source: https://habr.com/ru/post/1790124/


All Articles