本文主要是介绍简单回显客户端服务器应用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
服务器端:
import argparse
import socket
import syshost = "localhost"
data_payload = 2048
backlog = 5def echo_server( port ):sock = socket.socket( family = socket.AF_INET,type = socket.SOCK_STREAM )sock.setsockopt( socket.SOL_SOCKET,socket.SO_REUSEADDR,1 )server_addr = ( host, port )print "server: %s, port: %s" % server_addrsock.bind( server_addr )sock.listen( backlog )while True:print "Waiting from client."client, addr = sock.accept()data = client.recv( data_payload )if data:print "Data: %s" % dataclient.send( data )print "Sent %s bytes back to %s" % ( data, addr )client.close()if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument( "--port",action = "store",dest = "port",type = int,required = True )args = parser.parse_args()port = args.portecho_server( port )
客户端:
import socket
import sys
import argparsehost = "localhost"def echo_client( port ):sock = socket.socket( family = socket.AF_INET,type = socket.SOCK_STREAM )server_addr = ( host, port )print "Connecting to %s port %s" % server_addrsock.connect( server_addr )try:msg = "Test message. This will be echoed."print "Sending %s" % msgsock.sendall( msg )amount_received = 0amount_excepted = len( msg )while amount_received < amount_excepted: data = sock.recv( 16 )print "==" * 20amount_received += len( data )print "Received: %s" % dataexcept socket.errno, e:print "Socket error: %s" % str( e )except Exception, e:print "Other exception: %s" % str( e )finally:print "Closing connection"sock.close()if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument( "--port",action = "store",dest = "port",type = int,required = True )args = parser.parse_args()port = args.portecho_client( port )
这篇关于简单回显客户端服务器应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!