Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make the client connect with the server with socket multithread in python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "socket multithreading in python how to connect the client to the server", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let Xiaobian take you to learn "how to connect client and server with socket multithreading in python"!

Python socket multi-threaded client and server connection, for your reference, the details are as follows

Server Code:

import jsonimport socketimport threadingimport timeimport structclass Server(): def __init__(self): self.g_conn_pool = {} #connection pool #Record number of clients self.num =0 #Server Local Address self.address = ('0.0.0.0', 8000) #Initialize the server self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(self.address) self.server_socket.listen(128) def accept_client(self): """ Receive new connections """ while True: client_socket, info = self.server_socket.accept() #Block, waiting for client connection print(client_socket,port) #Create a separate thread for each client to manage thread = threading.Thread(target=self.recv_msg, args=(client_socket,info)) thread.setDaemon(True) thread.start() def recv_msg(self,client,info): #Prompt server open successfully print ('Server is ready! ') client.sendall("connect server successfully! ".encode(encoding='utf8')) #Continue accepting client connections while True: try: client.sendall(b'Success') while True: msg = client.recv(1024) msg_recv = msg.decode('utf-8') if not msg_recv: continue else: recv_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print ('client ' + recv_time + ':\n') print(' ' + msg_recv + '\n') except Exception as e: print ('Client Disconnect... ') exit(-1) break def start_new_thread(self): """Start a new thread to receive messages"" thread = threading.Thread(target=self.accept_client, args=()) thread.setDaemon(True) thread.start()

Server server class, mainly listening and receiving client information.

#Instantiate a Flask node app = Flask(__name__)@app.route ('/')def hello(): return 'hello'if __name__== '__main__': #Create parser from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-p', '--port', default=5030, type=int, help='port to listen on') args = parser.parse_args() #Get port number port = args.port #instantiate a server class and start py_server = Server() py_server.start_new_thread() #Start Flask node app.run(host='127.0.0.1',port=port)

Client Code

class Client(): def __init__(self): #Server ip and port self.server_address = ('127.0.0.1', 8000) self.num = 0 def recv_msg(self): print("Connecting to server... ") #Client connects to server while True: try: self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Connect Server self.client_socket.connect(self.server_address) num = self.num #Make a header header_dic = { 'filename': num } header_bytes = json.dumps(header_dic).encode('utf-8') self.client_socket.send(struct.pack('i', len(header_bytes))) self.client_socket.send(header_bytes) #Receive information while True: msg_recv = self.client_socket.recv(1024).decode('gbk') print(msg_recv) if msg_recv == 'Success': print ('The client has successfully established a connection with the server... ') elif not msg_recv: continue else: recv_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print ('server ' + recv_time +':\n') print(' ' + msg_recv + '\n') except: print ('Disconnect from server... ') break def start_new_thread(self): """Start a new thread to receive messages"" thread = threading.Thread(target=self.recv_msg, args=()) thread.setDaemon(True) thread.start() def main(): wf = Client() wf.start_new_thread() while True: a = input() wf.client_socket.send(a.encode('utf-8'))if __name__ == '__main__': main()

The above is the code for the client program.

Here are the results of the run:

Server side:

Multiple clients:

Code implementation is quite easy, specific can modify their own use.

At this point, I believe that everyone has a deeper understanding of "socket multithreading in python how to connect the client to the server", so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report