Python Network Programming first edition

Source: Internet
Author: User

--version 1 Only completes communication between the server/client.

1. Server-side code:

#!/usr/bin/python#!coding:utf-8 fromSocketImport*ImportOs,sysif __name__=="__main__":    #Defining Socketshostip='127.0.0.1'Port=2048sock=socket (Af_inet,sock_stream) Sock.bind ((Hostip,port)) Sock.listen (5)    Print '[INFO] start listening {0}:{1}'. Format (hostip,port) whileTrue:#accept a connection from a clientCONN,ADDR =sock.accept ()Print '[INFO] have recived a client from {0}'. Format (addr)#interacts with the client until the client exits         whileTrue:#receive information from clients, up to 1024 bytes at a timeRECIVEDDATA=CONN.RECV (1024)            #because the client sends an empty string when it disconnects, we use this to test that the connection is disconnected            if  notReciveddata:Print '[WAN] client has been disconnected ...'; Break; Print '[INFO] This is a infomation from client-to {0}'. Format (Reciveddata.decode ())#Send message to clientConn.send ('This inforamtion from server to {0}'. Format (Reciveddata.decode ()). Encode ()) Conn.close ()

2, the client side of the code:

#!/usr/bin/python#!coding:utf-8 fromSocketImport*ImportOs,sysif __name__=="__main__":    #Defining Socketshostip='127.0.0.1'Port=2048sock=socket (af_inet,sock_stream) messages=['Hello I am a client'] Messages=messages+sys.argv[1:] Sock.connect ((hostip,port))Print '[INFO] already connected to server'         forMessageinchMessages:sock.send (Message.encode ())PrintSOCK.RECV (1024). Decode () Sock.close ()

Python Network Programming first edition

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.