1. 程式人生 > 其它 >python併發程式設計之高併發下的tcp套接字程式設計

python併發程式設計之高併發下的tcp套接字程式設計

服務端

  import socket
  from  multiprocessing import  Process
  def task(sock):
      # 1024 bytes
      while True:
          # 客戶端非正常斷開,需要捕捉異常
          try:
              data = sock.recv(1024)
              if len(data) == 0:  # 當客戶端主動斷開時,接收的資料為空
                  break
              print(data)
              sock.send(data.upper())
          except Exception as e:
              print(e)
              break
      sock.close()
  if __name__ == '__main__':

      server = socket.socket()
      server.bind(('127.0.0.1',8080))
      server.listen(5)
      print("正在接收客戶端訊息:")
      while True:
          sock,addr = server.accept()
          print(sock)
          print(addr)
          p = Process(target=task,args=(sock,))
          p.start()

      server.close()

客戶端

    import socket
    client = socket.socket()
    client.connect(('127.0.0.1',8080))
    while True:
        input_data = input('請輸入要傳輸的資料:(q to quit)').strip()
        if not input_data:continue
        if input_data == 'q':
            break

        client.send(input_data.encode('utf-8'))
        data = client.recv(1024)
        print(data)
    client.close()