SoFunction
Updated on 2024-10-30

python write tcp client program using multithreading

Today, looking for half a day on the Internet, found that many of the programs on this topic can only receive data, so randomly find a program to study a little, and then make some changes

The code is as follows:

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('Received message as: %s' % recv_msg)


def send_msg(tcp_socket):
 global true
 while true:
  send_msg = input('Please enter the content to be sent')
  tcp_socket.send(send_msg.encode('utf-8'))
  if send_msg == "exit":
   true = False


def main():
 while True:
  print('*'*50)
  print('1 Send message \n2 Receive message')
  option = int(input('Please select the content of the operation'))
  print('*'*50)
  if option == 1:
   (target=send_msg, args=(tcp_socket,)).start()
  elif option == 2:
   (target=rece_msg, args=(tcp_socket,)).start()
  else:
   print('Input error')
  break


if __name__ == '__main__':
 main()

This code can only be implemented to either always send or always receive

Runs as shown

Screenshot when sending data

 

Screenshot when receiving data

 

To solve the problem of sending and receiving only unilaterally, the code is modified as follows

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('The message received is: %s\n' % recv_msg)


def send_msg(tcp_socket):
 global true
 while true:
  send_msg = input('Please enter the content to be sent\n')
  tcp_socket.send(send_msg.encode('utf-8'))
  if send_msg == "exit":
   true = False


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

running result

This is the whole content of this article.