Python memory-multi-threaded socket server

Source: Internet
Author: User
Tags ip number

On a sunny afternoon, think of the recent start from writing Java to writing Python, and then open your computer to experience the difference between Python and Java ~

Remember when I was a sophomore, that time to learn Java, the most interesting is the Java book the last chapter of the socket socket that part, the first time to see the opening of multiple black white shell interface appearance, then the excitement t.t~ that time still do not know what is multi-threading, One client has left the other clients out of work ... it would feel that multithreading is the most troublesome place I have ever learned .... It took one afternoon to get a multi-threaded socket program to play happily for a long time ~ ~

To say what I hate most about python, it must be that it does not have a Java method {}, instead of actually indentation .... This is where the spit is. T.T, this time to see the Python socket tutorial found and Java is similar, is still creating connections, customers and servers through the Send and Recv method communication, and finally closed, and in order to prevent a client and server connection caused by other client hangs phenomenon, I also deliberately added the Pyth On multithreading to ensure that this is not the case, I prefer to create threading for Python multi-Threading. The subclass of thread to wrap a thread object, maybe this is related to I often write Java ~ ~ ~ More familiar with this way, the following will be the server and the client code to paste out:

#Coding=utf-8ImportSocketImportthreading,getopt,sys,stringopts, args= Getopt.getopt (sys.argv[1:],"hp:l:",[" Help","port=","list="])#Set the default maximum number of connections and port numbers, and use the default values when no command is used to pass in parametersList=50Port=8001defusage ():Print """- h--help Print the Help-l--list Maximum number of connections-p--port To monitor the port number""" forOP, valueinchopts:ifOpinch("- L","--list"): List=String.atol (value)elifOpinch("- P","--port"): Port=String.atol (value)elifOpinch("- H"): Usage () sys.exit ()defJonnys (client, address):Try:    #setting the time-out periodClient.settimeout (500)    #the size of the received dataBUF = CLIENT.RECV (2048)    #returns the received information to the client as- isclient.send (BUF)#Show exit after timeout    exceptsocket.timeout:Print ' Time Out'    #Close the connection to the clientclient.close ()defMain ():#creates a socket object. Calling the socket constructor    #af_inet for IP address family, Sock_stream for stream socketsSock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#binds the socket to the specified address, the first parameter is the IP address, the second parameter is the port numberSock.bind (('localhost', Port)) #set the maximum number of connectionsSock.listen (list) whileTrue:#the server socket waits for a client to request a connection via the socket's Accept methodClient,address =sock.accept () thread= Threading. Thread (Target=jonnys, args=(client, address)) Thread.Start ()if __name__=='__main__': Main ()

In order to prevent excessive number of customers to cause behind the customer wait, I set the time-out, although not from the more to solve the problem, but can prevent some clients in vain to occupy the number of connections and not work, but also a total flattering solution ~ And by passing in the way of parameters can also be convenient to control the port number and the maximum number of connections allowed, although there is no examination of the system up to how many processes, but for a practice is enough, I hope someone knows the words welcome message tell me ha ~

The following are the client's:

#Coding=utf-8Importgetopt,socket,sys,stringopts, args= Getopt.getopt (sys.argv[1:],"hi:p:",[" Help","ip=","port="])#set the default IP address and port number and use the default value when no command is used to pass in parametershost="localhost"Port=8001defusage ():Print """- h--help Print the Help-i--ip Enter the IP address to connect-p--port Enter the port number to connect""" forOP, valueinchopts:ifOpinch("- I.","--ip"): Host=valueelifOpinch("- P","--port"): Port=String.atol (value)elifOpinch("- H"): Usage () sys.exit ()defMain ():#creates a socket object. Calling the socket constructor#af_inet for IP address family, Sock_stream for stream socketsSock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)#set the IP number and port number of the server you want to connect toSock.connect ((host, port))#The client enters a string to the serverMessage = Raw_input ("Inupt:")    #pdb.set_trace ()sock.send (message)Print 'Serveroupt:'+ SOCK.RECV (2048)#Close the connection to the serversock.close ()if __name__=='__main__': Main ()

The client is relatively simple, a very simple read user input, send to the server and then receive back such a simple function, after setting up the encoding of Chinese what is also possible ~ it is worth noting that the RECW () method set the size of the send, too small will be an error ~

In general and I first use Java to achieve the time is now easier and easier, but also just can take this opportunity to brush up on the past knowledge ~ Learning without thinking is not, thinking and not learning is dangerous!

Python memory-multi-threaded socket server

Related Article

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.