Python socket programming

Source: Internet
Author: User

Steps for Python to write server:

1. The first step is to create the socket object and call the socket constructor. Such as:

Socket = Socket.socket (family, type)

The family parameter represents the address family, which can be either af_inet or Af_unix. The Af_inet family includes af_inet and AF_INET6 for inter-network communication, and the Af_unix family is used for interprocess communication on the same machine.

The type parameter represents a socket type, including SOCK_STREAM (stream sockets) and Sock_dgram (datagram sockets).

2. The second step is to bind the socket to the specified address. This is done through the bind method of the Socket object:

Host if the local computer, you can give the IP address, you can also directly to the ""

HOST = ""

PORT = 50000

ADDR = (host,port)

Socket.bind (ADDR)

The socket created by AF_INET, the 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. The third step is to receive the connection request using the Listen method of the socket socket.

Socket.listen (Backlog)

The backlog specifies the maximum number of clients that are allowed to connect to the server. 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 fourth step is that 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 address is the client's IP address.

5. The fifth step is the processing stage where the server and the client communicate via the Send and Recv methods (transmit data).

Bufsiz = 1024

data = CONNECTION.RECV (Bufsiz)

The server uses the Recv method to receive information from the customer, and 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).

Connection.send (Data + "received")

The server calls send and sends a message to the client in string form, and the Send method returns the number of characters sent.

6. When the transfer is complete, the server calls the Close method of the socket to close the connection.

Steps for Python to write the client:

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:

HOST = "192.168.1.102"

PORT = 50000

ADDR = (host,port)

Socket.connect (ADDR)

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. During the processing phase, the client and the server communicate via the Send method and the Recv method.

Send_data = Raw_input (' > ')

Socket.send (data)

Recv_data = Socket.recv ()

4. When the transfer is complete, the client closes the connection by calling the Close method of the socket.

Socket.close ()

Here's a simple example:

server.py

#coding =utf-8from Socket Import *import timehost = "" PORT = 50000BUFSIZ = 1024ADDR = (host,port) # Socket definition method: socket (SOCKET_FA Mily,socket_type,protocol = 0) # There are two types of sockets: file-based Af_unix (Af_local is upgraded) and network-based af_inet# each socket can be divided into connection-oriented sock_stream, Non-connected Sock_dgramtcpserversock = socket (Af_inet,sock_stream) # bind address (hostname, port) to socket Tcpserversock.bind (ADDR) # listen () Indicates the maximum number of connections allowed to come in, and the latter will be rejected. Tcpserversock.listen (5) while True:print "Waiting for connection ..." # Accept (Socket object, address info)      Wait for the incoming connection.      # Return A new socket representing the connection, and the address of the client.    # for IP sockets, the address info is a pair (hostaddr, port). TCPCLIENTSOCK,ADDR = Tcpserversock.accept () # tcpclientsock.settimeout (5) print "... connected from:", addr Thistim        E = Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ()) while True: # recv (buflen[, Flags])--Receive data        data = TCPCLIENTSOCK.RECV (bufsiz) if not data:breakPrint (Thistime + "receive:" + Data + ") tcpclientsock.send (Thistime + ': ' + data ') if data = = ': Tcpclientsock.close () Tcpserversock.close ()

client.py

From socket import *host = "127.0.0.1" PORT = 50000BUFSIZE = 1024ADDR = (host,port) socketclient = socket (Af_inet,sock_strea M) Socketclient.connect (ADDR) while true:data = Raw_input (' > ') if not data:breaksocketclient.send (data) data = SOCKETCLIENT.RECV (BUFSIZE) if not data:breakprint datasocketclient.close ()

  

  

Python socket programming

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.