欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python使用多線程編寫(xiě)tcp客戶端程序

 更新時(shí)間:2019年09月02日 08:40:32   作者:bai_yun_123  
這篇文章主要為大家詳細(xì)介紹了python使用多線程編寫(xiě)tcp客戶端程序,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

今天在網(wǎng)上找了半天,發(fā)現(xiàn)很多關(guān)于此題目的程序都只能接收數(shù)據(jù),所以隨便找了個(gè)程序研究了一下,然后做出一些修改

代碼如下:

from socket import *
import threading
tcp_socket = socket(AF_INET, SOCK_STREAM)
tcp_socket.connect(('192.168.1.102', 8080))
true = True


def rece_msg(tcp_socket):
 global true
 while true:
  recv_msg = tcp_socket.recv(1024).decode("utf8")
  if recv_msg == "exit":
   true = False
  print('接收到的信息為:%s' % recv_msg)


def send_msg(tcp_socket):
 global true
 while true:
  send_msg = input('請(qǐng)輸入要發(fā)送的內(nèi)容')
  tcp_socket.send(send_msg.encode('utf-8'))
  if send_msg == "exit":
   true = False


def main():
 while True:
  print('*'*50)
  print('1 發(fā)送消息\n2 接收消息')
  option = int(input('請(qǐng)選擇操作內(nèi)容'))
  print('*'*50)
  if option == 1:
   threading.Thread(target=send_msg, args=(tcp_socket,)).start()
  elif option == 2:
   threading.Thread(target=rece_msg, args=(tcp_socket,)).start()
  else:
   print('輸入有誤')
  break


if __name__ == '__main__':
 main()

該代碼只能實(shí)現(xiàn)要么一直發(fā)送,要么一直接收

運(yùn)行如圖

發(fā)送數(shù)據(jù)時(shí)截圖

 

接收數(shù)據(jù)時(shí)截圖

 

為解決只能單方發(fā)送和接收問(wèn)題,現(xiàn)將代碼修改如下

from socket import *
import threading
tcp_socket = socket(AF_INET, SOCK_STREAM)
tcp_socket.connect(('192.168.1.102', 8080))
true = True


def rece_msg(tcp_socket):
 global true
 while true:
  recv_msg = tcp_socket.recv(1024).decode("utf8")
  if recv_msg == "exit":
   true = False
  print('接收到的信息為:%s\n' % recv_msg)


def send_msg(tcp_socket):
 global true
 while true:
  send_msg = input('請(qǐng)輸入要發(fā)送的內(nèi)容\n')
  tcp_socket.send(send_msg.encode('utf-8'))
  if send_msg == "exit":
   true = False


threading.Thread(target=send_msg, args=(tcp_socket,)).start()
threading.Thread(target=rece_msg, args=(tcp_socket,)).start()

運(yùn)行結(jié)果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論