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设计】。

相关文章

pytyon 带有重复的全排列

复制代码 代码如下:from sys import argvscript, start, end = argvvis = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...

Flask 上传自定义头像的实例详解

Flask 上传自定义头像的实例详解

Flask Web 开发这本书基本上做完了,后面还需要温习,但是自己做的博客总觉得简陋了点,所以,在动脑子开发新功能 今天想到最基本的功能,自定义头像 那这样的功能,设计到2大基本功能块...

Python Django 命名空间模式的实现

Python Django 命名空间模式的实现

新建一个项目 app02 在 app02/ 下创建 urls.py: from django.conf.urls import url from app02 import view...

用scikit-learn和pandas学习线性回归的方法

用scikit-learn和pandas学习线性回归的方法

对于想深入了解线性回归的童鞋,这里给出一个完整的例子,详细学完这个例子,对用scikit-learn来运行线性回归,评估模型不会有什么问题了。 1. 获取数据,定义问题 没有数据,当然没...

Python3.5 创建文件的简单实例

实例如下所示: #coding=utf-8 ''' Created on 2012-5-29 @author: xiaochou ''' import os import time...