1 TCP服务端

  1. from socket import *
  2. from threading import Thread
  3. class TcpServer():
  4. def __init__(self, host, port):
  5. self.server = socket()
  6. self.server.bind((host, port))
  7. self.server.listen()
  8. def start(self):
  9. while True:
  10. print('正在等待新客户端...')
  11. conn, addr = self.server.accept()
  12. Thread(target=self.handle, args=(conn,), daemon=True).start()
  13. def handle(self, conn: socket):
  14. while True:
  15. print('正在等待客户端发送...')
  16. try:
  17. data = conn.recv(1024)
  18. except:
  19. data = b''
  20. data = data.decode()
  21. if data == '':
  22. print('客户端{}断开连接'.format(conn.getpeername()))
  23. conn.close()
  24. return
  25. print('收到客户端的消息:', data)
  26. conn.send('hello'.encode())
  27. server = TcpServer('192.168.3.67', 9000)
  28. server.start()

2 TCP客户端

  1. from socket import *
  2. class TcpClient():
  3. def __init__(self, host, port):
  4. self.client = socket()
  5. self.client.connect((host, port))
  6. def send_recv(self, msg: str):
  7. self.client.send(msg.encode())
  8. response = self.client.recv(1024).decode()
  9. return response
  10. cli = TcpClient('192.168.3.67', 9000)
  11. response = cli.send_recv('hi')
  12. print(response)

3 WireShark抓包

  • 服务端:192.168.3.67
  • 客户端:192.168.3.47

image.png