Python Socket Communication ~ Simple instance

Source: Internet
Author: User

Socket programming Steps
    1. The server creates a socket, binds the address and port, and listens for incoming connections on the port, and receives the incoming connection through the Accept function once the connection comes in.
    2. The client is also creating a socket. Bind the remote address and port, and then establish the connection to send the data.

  

Family address cluster, with the first parameter of the socket () function. Mainly has the following several

    1. Socket.af_unix communication with processes under a single machine
    2. Socket.af_inet communicates with the server, usually using this.
    3. SOCKET.AF_INET6 Support IPV6

The SocketType socket type, used with the second parameter of the socket () function, is commonly used to have

    1. Socket. Sock_stream default, for TCP protocol
    2. Socket. Sock_dgram for UDP protocol

Service side

ImportSocketserver=socket.socket () Server.bind ('127.0.0.1', 6969) ) Server.listen ()#Start listening .#The conn is a connection instance that the client is connecting to and is generated on the server.conn, addr = Server.accept ()#Wait for session link#print (conn,addr) # Printing to view conn,addr content#receiving Datadata = CONN.RECV (1024)#Print receive DataPrint('recv:', data)#Return DataConn.send (Data.upper ())

Client

ImportSocket#declares the socket type and generates the socket connection object at the same timeClient =Socket.socket ()#Start ConnectionClient.connect (('127.0.0.1', 6969))#Send Message Note 3. Only binary data can be sent in the above versionClient.send (b'Test Socket')#Receive Datadata = CLIENT.RECV (1024)#Print receive DataPrint('recv:', data)#Close ConnectionClient.close ()

Python Socket Communication ~ Simple instance

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.