Python---a Simple Socket

Source: Internet
Author: User

Server side:

1 Create a Socket object. Call the socket Constructor. Such as:

Socket = Socket.socket (family, Type)
#family参数代表地址家族, can be af_inet or af_unix. The Af_inet family includes internet addresses, and the Af_unix family is used for interprocess communication on the same MACHINE.
The #type参数代表套接字类型 can be sock_stream (stream sockets) and Sock_dgram (datagram sockets).

2 binds the socket to the specified address. This is done through the bind method of the socket object:

Socket.bind (address)

#由AF_INET所创建的套接字, address must be a two-element tuple in the format (host,port). host, Port represents the port Number. The Bind method throws an Socket.error exception if the port number is in use, the hostname is incorrect, or the port has been persisted.

3 A connection request is received using the Listen method of the socket Socket.

Socket.listen (backlog)
#backlog指定最多允许多少个客户连接到服务器. It has a value of at least 1. When a connection request is received, the requests are queued and the request is rejected if the queue is Full.

4 The server socket waits for the client to request a connection through the Socket's accept Method.

connection, address = socket.accept ()
When the Accept method is called, the socket is in the "waiting" State. When a client requests a connection, the method establishes the connection and returns the Server. The Accept method returns a tuple containing two elements (connection,address). The first element, connection, is the new socket object that the server must communicate with the customer, and the second element address is the Customer's Internet Location.

5 processing phase, The server and the client communicate via the Send and Recv methods (transfer data). The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to receive information from the Customer. When calling recv, the server must specify an integer that corresponds to the maximum amount of data that can be received through this method Call. The Recv method enters the "blocked" state when it receives the data, and finally returns a string that represents the received Data. If the amount of data sent exceeds the allowable recv, the data will be Truncated. The excess data will be buffered on the receiving Side. When Recv is called later, the extra data is removed from the buffer (and any other data that the customer may have sent since the last call to Recv).

6 The transfer ends, The server calls the Close method of the socket to close the Connection.

Client Side:

1 Create a socket to connect to the Server:

Socket = Socket.socket (family, Type)

2 Connect to the server using the Connect method of the Socket. For the af_inet family, the connection format is as Follows:

Socket.connect ((host,port))

Host represents the server host name or ip,port the port number that is bound on behalf of the server Process. If the connection succeeds, the client can communicate with the server through the socket, and if the connection fails, a Socket.error exception is Thrown.

3 processing phase, The client and the server will communicate through the Send method and the recv Method.


4 The end of the transfer, the client closes the connection by calling the Close method of the Socket.

Code:

server.py

if __name__=='__main__':      ImportSocket sock=Socket.socket (socket.af_inet, Socket. Sock_stream) Sock.bind (('localhost', 8001)) Sock.listen (5)       whiletrue:connection,address=sock.accept ()Try: Connection.settimeout (5) BUF= Connection.recv (1024)              ifBUF = ='1': Connection.send ('Welcome to server!')              Else: Connection.send ('please Go out!')          exceptsocket.timeout:Print ' time out'connection.close ()

client.py

if __name__=='__main__':      ImportSocket sock=Socket.socket (socket.af_inet, Socket. Sock_stream) Sock.connect (('localhost', 8001))      Importtime Time.sleep (2) Sock.send ('1')      PrintSock.recv (1024) Sock.close ()

Running server.py at the terminal and then running clien.py will print "welcome to server!" at the Terminal. If you change Client.py's sock.send (' 1 ') to another value in the terminal will print "please go out!",

Python---a Simple Socket

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.