From socket import * # import all the content in the socket package from time import ctime # import the time package. At the same time, you can use ctime to call import thread # import the Python thread package
HOST = 'localhost' # define host port = 21567 # Define port bufsiz = 1024 # define buffer ADDR = (HOST, PORT) # define tuples
TcpSerSock = socket (AF_INET, SOCK_STREAM) # generate sockettcpSerSock. bind (ADDR) # bind the address and port tuples to the socket tcpSerSock. listen (1) # listen to user requests
Def client (tcpCliSock, num): # define a function. Because thread forcibly requires that the called function must have two parameters. Num is only a charge. It has no special meaning. CliSock = tcpCliSock # assign the passed client socket to CliSock while True: # define Infinite Loop data = CliSock. recv (BUFSIZ) # Read 1024 data in size from user socket if not data: # if the client does not have any input, press ENTER or Ctrl + D break # Jump out of the infinite loop CliSock. send ('[% s] % s' % (ctime (), data) # Return the user input and append the current system time sys. exit # terminate a process
While True: # define an infinite loop print "waiting .... "# print the waiting tcpCliSock, addr = tcpSerSock waiting for user input. accept () # process user request print 'Con from: ', addr # print client information thread. start_new_thread (client, (tcpCliSock, 1) # Use the thread in Python! Python will start a new thread to run the client function and pass it to this function parameter in the form of tuples!
TcpSerSock. close () # This sentence is still not executed!
Threading is a module officially recommended for writing threads. It is still necessary to understand the thread, which not only gives us a better understanding of the running mode of system threads, but also finds the difference between thread and threading and Queue, so as to better understand threading!
The following is a Python client program. If you can use telnet for testing, you can ignore the following content. From socket import *
HOST = 'localhost' PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT)
TcpCliSock = socket (AF_INET, SOCK_STREAM) tcpCliSock. connect (ADDR)
While True: data = raw_input (">") if not data: break tcpCliSock. send (data) data = tcpCliSock. recv (BUFSIZ) if not data: break print data
TcpCliSock. close ()
This article is from the "Lincoln" blog, please be sure to keep this source http://president.blog.51cto.com/4990508/1081542