且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的客户端-服务器通信

更新时间:2021-11-27 21:59:45

服务器端添加了一些保护.也许这就是您所需要的?客户端进程完成后,服务器将继续侦听连接.通过启动服务器,启动客户端,发送消息,再次启动客户端并发送另一条消息来尝试...

Server side with a little protection added. Perhaps this is what you need? The server will continue to listen for connections after the client process finishes. Try it by starting the server, starting the client, sending a message, starting the client again and sending another message...

import socket
import threading
import sys

s = socket.socket()                      # Create a socket object
host = socket.gethostname()              # Get local machine name

port = 12345                             # Reserve a port for your service.
s = socket.socket()
s.bind((host, port))                     # Bind to the port

s.listen(5)                              # Now wait for client connection.

def processMessages(conn, addr):
    while True:
        try:
            data = conn.recv(1024)
            if not data: 
                conn.close()
            print(data.decode("utf-8"))
            conn.sendall(bytes('Thank you for connecting', 'utf-8'))
        except:
            conn.close()
            print("Connection closed by", addr)
            # Quit the thread.
            sys.exit()


while True:
    # Wait for connections
    conn, addr = s.accept()
    print('Got connection from ', addr[0], '(', addr[1], ')')
    # Listen for messages on this connection
    listener = threading.Thread(target=processMessages, args=(conn, addr))
    listener.start()