From socket import * # import all 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 Python thread package HOST = 'localhost' # define host port = 21567 # Define port bufsiz = 1024 # define buffer ADDR = (HOST, PORT) # define tcpSerSock = socket (AF_INET, SOCK_STREAM) # generate sockettcpSerSock. bind (ADDR) # bind the address and port tuples to the socket tcpSerSock. listen (1) # listen to the user request 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 # End process while True: # define 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. sta Rt_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=21567BUFSIZ=1024ADDR=(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()
Address: http://president.blog.51cto.com/4990508/1081542