Sending string via socket (python)

后端 未结 3 567
予麋鹿
予麋鹿 2020-11-30 23:32

I have two scripts, Server.py and Client.py. I have two objectives in mind:

  1. To be able to send data again and again to server from client.
  2. To be ab
3条回答
  •  不知归路
    2020-12-01 00:22

    import socket
    from threading import *
    
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "192.168.1.3"
    port = 8000
    print (host)
    print (port)
    serversocket.bind((host, port))
    
    class client(Thread):
        def __init__(self, socket, address):
            Thread.__init__(self)
            self.sock = socket
            self.addr = address
            self.start()
    
        def run(self):
            while 1:
                print('Client sent:', self.sock.recv(1024).decode())
                self.sock.send(b'Oi you sent something to me')
    
    serversocket.listen(5)
    print ('server started and listening')
    while 1:
        clientsocket, address = serversocket.accept()
        client(clientsocket, address)
    

    This is a very VERY simple design for how you could solve it. First of all, you need to either accept the client (server side) before going into your while 1 loop because in every loop you accept a new client, or you do as i describe, you toss the client into a separate thread which you handle on his own from now on.

提交回复
热议问题