python使用多線程編寫tcp客戶端程序
更新時間:2019年09月02日 08:40:32 作者:bai_yun_123
這篇文章主要為大家詳細介紹了python使用多線程編寫tcp客戶端程序,具有一定的參考價值,感興趣的小伙伴們可以參考一下
今天在網上找了半天,發(fā)現很多關于此題目的程序都只能接收數據,所以隨便找了個程序研究了一下,然后做出一些修改
代碼如下:
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('請輸入要發(fā)送的內容') 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('請選擇操作內容')) 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()
該代碼只能實現要么一直發(fā)送,要么一直接收
運行如圖
發(fā)送數據時截圖
接收數據時截圖
為解決只能單方發(fā)送和接收問題,現將代碼修改如下
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('請輸入要發(fā)送的內容\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()
運行結果
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python3 socket即時通訊腳本實現代碼實例(threading多線程)
- python使用多線程+socket實現端口掃描
- 解決python ThreadPoolExecutor 線程池中的異常捕獲問題
- 解決python多線程報錯:AttributeError: Can''t pickle local object問題
- python實現自動化報表功能(Oracle/plsql/Excel/多線程)
- python多線程實現TCP服務端
- Python實現多線程/多進程的TCP服務器
- Python3多線程版TCP端口掃描器
- python單線程下實現多個socket并發(fā)過程詳解
- 詳解C語言和Python中的線程混用
相關文章
Python WXPY實現微信監(jiān)控報警功能的代碼
本篇文章主要介紹了Python WXPY實現微信監(jiān)控報警功能的代碼,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10