基础部分
server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import socket
def socket_server(): HOST = '0.0.0.0' PORT = 5001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) print("listening ... ") while 1: conn, addr = s.accept() print('Connected by', addr) conn.send(bytes("Connected success", encoding='utf-8')) while 1: data = str(conn.recv(1024), encoding='utf-8') print(data) conn.close()
if __name__ == "__main__": socket_server()
|
client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import socket
def socket_client(): HOST = '127.0.0.1' PORT = 5001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) data = s.recv(1024) print(data) while 1: cmd = input("Please input cmd:") s.send(bytes(cmd, encoding='utf-8')) s.close()
if __name__ == "__main__": socket_client()
|
Python实现一个服务端,多个客户端接入
服务器端
服务器端每一次接收客户端连接,都要fork一个进程来完成,如果单纯使用socket模块来实现,是不容易完成多线程接入的。为了方便,可以直接使用socketserver 模块。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from socketserver import BaseRequestHandler, ThreadingTCPServer
class Handler(BaseRequestHandler):
def handle(self) -> None: address, pid = self.client_address print(f'{address} connected!') while True: data = self.request.recv(1024) if len(data) <= 0: print("close!") break print(f'receive data: {data.decode()}') self.request.sendall('response'.encode())
if __name__ == '__main__': server = ThreadingTCPServer(('127.0.0.1', 8998), Handler) print("Listening") server.serve_forever()
|
客户端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import socket
class Client: def __init__(self): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, server_ip, server_port): self.client.connect((server_ip, server_port))
def run(self): while True: print("please input:") message = input() self.client.sendall(message.encode()) response = self.client.recv(1024) print(response.decode())
if __name__ == '__main__': client = Client() client.connect('127.0.0.1', 8998) client.run()
|