Python Network programming socket Multi-threading

Source: Internet
Author: User

#coding: utf-8__author__ = ' similarface ' import os,socket,threading,socketserverserver_host= ' localhost ' server_port= 0buf_size=1024echo_msg= ' HELLO ' class Threadclient (): Def __init__ (self,ip,port): #建立sock self.sock=socket. Socket (Socket.af_inet,socket. SOCK_STREAM) #连接server Self.sock.connect ((ip,port)) def run (self): #获取当前的进程号 current_proces S_id=os.getpid () print ' PID%s: ' '%s ' '% (current_process_id,echo_msg) sent_data_length = Self.sock.send (ECHO        _msg) print (' Send:%d Long data '% sent_data_length) #sever response Response=self.sock.recv (buf_size) Print "PID%s Received:%s"% (Current_process_id,response) def shutdown (self): "Cleanup sock resources: RET urn: "' self.sock.close () class Forkingserverrequesthandler (Socketserver.baserequesthandler): Def handle (        Self): #接受客户端的数据 data=self.request.recv (buf_size) #当前的进程号码 #current_process_id =os.getpid ()Current_thread = Threading.current_thread () #返回的数据包 response= '%s:%s '% (current_thread.name, data) p Rint "Server returned [Current_process_id:data] =[%s]"%response #发送返回数据 self.request.send (response) Returncla SS Forkingserver (Socketserver.threadingmixin,socketserver.tcpserver): Passdef main (): #建立server server=forkingser Ver ((server_host,server_port), Forkingserverrequesthandler) #获取IP and port IPs, port = server.server_address # Retrieve th E port number #服务进程 Server_thread = Threading. Thread (target=server.serve_forever) #是否放入后台 Server_thread.setdaemon (True) # don ' t hang on exit #启动 Server_thre Ad.start () print ' Server loop running PID:%s '%os.getpid () # Launch the client (s) client1 = threadclient (IP, PO RT) Client1.run () Client2 = threadclient (IP, Port) client2.run () # Clean them up server.shutdown () Clie Nt1.shutdown () Client2.shutdown () server.socket.close () if __name__ = = ' __main__ ': MaiN () 

  

Python Network programming socket Multi-threading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.