1 TCP服务端
from socket import *
from threading import Thread
class TcpServer():
def __init__(self, host, port):
self.server = socket()
self.server.bind((host, port))
self.server.listen()
def start(self):
while True:
print('正在等待新客户端...')
conn, addr = self.server.accept()
Thread(target=self.handle, args=(conn,), daemon=True).start()
def handle(self, conn: socket):
while True:
print('正在等待客户端发送...')
try:
data = conn.recv(1024)
except:
data = b''
data = data.decode()
if data == '':
print('客户端{}断开连接'.format(conn.getpeername()))
conn.close()
return
print('收到客户端的消息:', data)
conn.send('hello'.encode())
server = TcpServer('192.168.3.67', 9000)
server.start()
2 TCP客户端
from socket import *
class TcpClient():
def __init__(self, host, port):
self.client = socket()
self.client.connect((host, port))
def send_recv(self, msg: str):
self.client.send(msg.encode())
response = self.client.recv(1024).decode()
return response
cli = TcpClient('192.168.3.67', 9000)
response = cli.send_recv('hi')
print(response)
3 WireShark抓包
- 服务端:192.168.3.67
- 客户端:192.168.3.47