目的

掌握socket客户端与服务器端的通讯连线

实现

两客户端连接服务器端进行通讯

代码

客户端

  import socket
  
  while True:
      client = socket.socket()
      client.connect((socket.gethostname(), 8899))
      data = "客户1: " + input("正在输入:")
      client.sendall(data.encode("utf-8"))
      client.close()

服务器

 import socket
import time
import socketserver
 
   class MyTCPHandler(socketserver.BaseRequestHandler):
      def handle(self):
        try:
            while True:
                self.data = self.request.recv(1024)
                print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), self.data.decode())
              if not self.data:
                  print("connection lost")
                  break
              self.request.sendall(self.data.upper())
      except Exception as e:
          print(self.client_address, "连接断开")
      finally:
          self.request.close()

  def setup(self):
      print("before handle,连接建立:", self.client_address)

  def finish(self):
      print("finish run  after handle")


if __name__ == "__main__":
    HOST, PORT = socket.gethostname(), 8899
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
"""
server = socket.socket()
server.bind((socket.gethostname(), 8899))
server.listen(5)
print("服务器已经启动!")

while True:
    client, addr = server.accept()
    data = client.recv(1024)
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), data.decode())
    client.close()

"""