python使用多线程编写tcp客户端程序

yipeiwu_com6年前Python基础

今天在网上找了半天,发现很多关于此题目的程序都只能接收数据,所以随便找了个程序研究了一下,然后做出一些修改

代码如下:

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()

运行结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python进程间通信之共享内存详解

前一篇博客说了怎样通过命名管道实现进程间通信,但是要在windows是使用命名管道,需要使用python调研windows api,太麻烦,于是想到是不是可以通过共享内存的方式来实现。查...

Python 多核并行计算的示例代码

Python 多核并行计算的示例代码

以前写点小程序其实根本不在乎并行,单核跑跑也没什么问题,而且我的电脑也只有双核四个超线程(下面就统称核好了),觉得去折腾并行没啥意义(除非在做IO密集型任务)。然后自从用上了32核128...

Python通过Django实现用户注册和邮箱验证功能代码

本文主要向大家分享了Python编程中通过Django模块实现用户注册以及邮箱验证功能的简单介绍及代码实现,具体如下。 用户注册: 类似于用户登陆,同样在users.views.py中添...

Python实现获取某天是某个月中的第几周

找了半天竟然没找到,如何在Python的datetime处理上,获取某年某月某日,是属于这个月的第几周。 无奈之下求助同学,同学给写了一个模块。【如果你知道Python有这个原生的库,请...

Python网页解析利器BeautifulSoup安装使用介绍

Python网页解析利器BeautifulSoup安装使用介绍

python解析网页,无出BeautifulSoup左右,此是序言 安装 BeautifulSoup4以后的安装需要用eazy_install,如果不需要最新的功能,安装版本3就够了,千...