Python2.7 _ 1.14 _ compile a simple echo Client/Server application, and python2.7 _ 1.14 echo
1. server. py
#-*-Coding: UTF-8-*-import socketimport argparsehost = 'localhost' data _ payload = 2048 backlog = 5def echo_server (port): # create a TCP server sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # set socket reuse sock. setsockopt (socket. SOL_SOCKET, socket. SO_REUSEADDR, 1) # bind the socket to the port server_address = (host, port) print 'starting up echo server on % s port % s' % server_address sock. bind (server_address) # Listen to the client and set the backlog value to sock, the maximum number of the connection sequence. listen (backlog) while True: print 'waiting to receive message from client 'client, address = sock. accept () data = client. recv (data_payload) if data: print 'receive Data: % s '% data # returned processed data =' <worked> '+ data +' </worked> 'client. send (data) print 'sent % s bytes back to % s' % (data, address) # Disconnect the client. close () if _ name _ = '_ main _': parser = argparse. argumentParser (description = 'socket Server Example ') parser. add_argument ('-- port', action = 'store', dest = 'Port', type = int, required = True) given_args = parser. parse_args () port = given_args.port echo_server (port)
2. client. py
#-*-Coding: UTF-8-*-import socketimport argparsehost = 'localhost' def echo_client (port): sock = socket. socket (socket. AF_INET, socket. SOCK_STREAM) server_address = (host, port) print 'ing ing to % s port % s' % server_address sock. connect (server_address) try: message = 'I am a programmer' # convert the content into GBK-encoded message = message in the CMD window. decode ('utf-8 '). encode ('gbk') print 'sending: % s' % message sock. sendall (message) amount_received = 0 amount_expected = len (message) while amount_received <amount_expected: data = sock. recv (16) amount_received + = len (data) print 'stored ed: % s' % data failed t socket. error, e: print 'socket error: % s' % str (e) failed t Exception, e: print 'other error: % s' % str (e) finally: print 'closing connection to the Server' sock. close () if _ name _ = '_ main _': parser = argparse. argumentParser (description = 'socket Server Example ') parser. add_argument ('-- port', action = 'store', dest = 'Port', type = int, required = True) given_args = parser. parse_args () port = given_args.port print port echo_client (port)
3. Run
Python server. py -- port = 9900
Python client. py -- port = 9900