python使用多线程编写tcp客户端程序
今天在网上找了半天,发现很多关于此题目的程序都只能接收数据,所以随便找了个程序研究了一下,然后做出一些修改
代码如下:
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('请输入要发送的内容') tcp_socket.send(send_msg.encode('utf-8')) if send_msg == "exit": true = False def main(): while True: print('*'*50) print('1 发送消息\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()
该代码只能实现要么一直发送,要么一直接收
运行如图
发送数据时截图
接收数据时截图
为解决只能单方发送和接收问题,现将代码修改如下
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('请输入要发送的内容\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()
运行结果
相关推荐
farewellpoem 2020-11-09
lhtzbj 2020-08-13
learnpy 2020-07-19
kyelu 2020-07-09
举 2020-06-14
haokele 2020-05-31
fengling 2020-05-31
maimang00 2020-05-30
坚持是一种品质 2020-05-28
laityc 2020-05-27
jling 2020-05-19
YENCSDN 2020-05-14
singer 2020-04-30
举 2020-04-29
学习备忘录 2020-04-20
CloudXli 2020-04-07
瓜牛呱呱 2020-11-12
starinshy 2020-11-10
huichen 2020-10-13