Python socket TCP Server and client demo
Author: Vpoet
Date: Summer
Server
#-*-coding:cp936-*-"Creates a Python server that listens on the specified port and, if the port is accessed remotely, gets a remote connection, receives the data, and makes the appropriate feedback. "Import socketif __name__==" __main__ ": Print" Server is starting "sock = Socket.socket (socket.af_inet, socket. Sock_stream) sock.bind ((' localhost ', 8001)) #配置soket, bound IP address and port number Sock.listen (5) #设置最大允许连接数, the communication of each connection and server follows the FIFO principle Print "Server is listenting Port 8001, with Max connection 5" while True: #循环轮询socket状态, waiting for access connection , address = Sock.accept () try:connection.settimeout (Ten) #获得一个连接, and then begins to loop through the information sent by this connection If the server is going to handle multiple connections at the same time, the following block of statements should be handled with multithreading, otherwise the server will always be in the same block as the first connection, unable to scan the other new connections , but multithreading can affect the code structure, so remember that when the number of connections is greater than 1 o'clock, the statement is changed to multithreading. "While true:buf = Connection.recv (1024x768) print" Get value "+buf print "\ n" if buf== "Q": print "Exit server\n\n" break Except Socket.timeout: #如果建立连接后, the connection does not have data to be sent within the set time, then times out print ' "print" closing one Connect Ion "#当一个连接监听循环退出后, connection can be turned off connection.close ()
Client
Import sysif __name__== "__main__": import socket sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) sock.connect ((' localhost ', 8001)) import time while True: time.sleep (3) Flag=raw _input ("Please input send flag:") if flag== "Q": break sock.send (flag) sock.close ()
Run:
Python socket TCP Server and client demo