Python 簡單的用戶端/伺服器應用

來源:互聯網
上載者:User

標籤:

Server:

import socketimport sysimport argparsehost = ‘localhost‘data_payload = 2048backlog = 5def echo_server(port):‘‘‘A simple echo server‘‘‘#Create a TCP socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#Enable reuse address /portsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#Bind the socket to the portserver_address = (host, port)print "Starting up echo server on %s port %s " %server_addresssock.bind(server_address)#Listen to clients, backlog argument specifies the max number of queued connectionssock.listen(5)while True:print "Waiting to receive message from client"client, address = sock.accept()data = client.recv(data_payload)if data:print "Data: %s" %dataclient.send(data)print "send %s bytes back to %s" %(len(data), address)#End connectionclient.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.portecho_server(port)

  

 

 

Client:

import socketimport sysimport argparsehost = ‘localhost‘def echo_client(port):‘‘‘A simple echo client‘‘‘#Create a TCP/IP socketsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#Connect the socket to the serverserver_address = (host, port)print "Connecting to %s port %s"  %server_addresssock.connect(server_address)#Send datatry:#Send datamessage = "Test message. This will be echoed."print "Sending %s" %messagesock.sendall(message)#Look for the responseamount_received = 0amount_expected = len(message)while amount_received < amount_expected:data = sock.recv(16)amount_received +=len(data)print "Receviced :%s " %dataexcept socket.error, e:print "Socket error: %s"  %str(e)except Exception, e:print "Other exception: %s"  %str(e)finally:print "Closing connection to the server"sock.close()if __name__=="__main__":parser = argparse.ArgumentParser(description=‘Socket Client Example‘)parser.add_argument(‘--port‘, action=‘store‘, dest=‘port‘, type=int, required=True)given_args = parser.parse_args()port = given_args.portecho_client(port)

  

Python 簡單的用戶端/伺服器應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.