Python Network programming--tcp

Source: Internet
Author: User

<pre name= "code" class= "Python" >


First, network communication mode

For network traffic, the TCP/IP protocol group is now followed.

And now the design of the communication mode, the main use of client/server programming, the so-called client is the software used by our users, and the server is the program developers according to the needs of the client design service mode, in order to meet the requirements of the client, to achieve normal communication with the client.

Socket: Endpoint of communication

For the TCP/IP protocol, it is a multilayer protocol family, which are physical layer, data link layer, network layer, Transport layer, application layer, respectively. For the role of the network layer, mainly from one host in the network to find another host, and the role of the transport layer is in a host, select an application port (for a computer, may have to run many applications, the operating system left a lot of ports for processing each different application software).

1. Connection-oriented communication (TCP)

The so-called connection-oriented communication, that is, based on the TCP protocol communication mode. This approach is a sequential, reliable, and not repetitive transmission mode.

2. Non-connected communication (UDP)

Data can be communicated without establishing a connection.

Third, TCP-based network programming

TCP Server side:

1. The first step is to create the socket object. 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 Internet addresses, and the Af_unix family is used for interprocess communication on the same machine.
The type parameter represents a socket type, which can be 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:
Socket.bind (Address)
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 element address is the customer's Internet location.
5. The fifth step is the processing stage where the server and the client communicate via the Send and Recv methods (transmit 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. Transfer end, the server calls the socket's Close method to close the connection

The pseudo-code is roughly as follows:

1 Create sockets, bind sockets to local addresses, and then start listening for connections. Is Socket,bind,listen.

2 into the loop, continue to accept the client connection request, and then receive the data transmitted, of course, can also be sent to the data. is to accept a connection and then recv the data.

3 receive finished can close the socket, close.

Ss.socket (Socket.af_inet,socket.sock_stram) #创建服务器套接字

Ss.bind () #把本地地址绑到套接字上

Ss.listen () #监听连接

inf_loop: #服务器无限循环

Cs=ss.accept () #接受客户端的连接

Comm._loop: #通信循环

CS.RECV ()/cs.send () #对话

Cs.close () #关闭客户套接字

Ss.close () #关闭服务器套接字



<pre name= "code" class= "python" >post = ' host IP ' port = 8899bufsiz = 1024addr = (post,port) Tcpsersock = socket (af_inet,s Ock_stream) tcpsersock.bind (addr) Tcpsersock.listen (5) while True:    print ' Wait client Conncet '    tcpclient,addr =tcpsersock.accept ()    print ' Connect from ', addr and    True:        data = TCPCLIENT.RECV (bufsiz)        if not data:            break        tcpclient.send (' [%s]%s '% (CTime (), data)) #        Tcpclient.close () tcpsersock.close ()



TCP Client:

1. The first step is to create a socket to connect to the server: socket = socket.socket (family, type)
2. The second step is to 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. The third step is the processing phase, in which the client and the server communicate via the Send method and the Recv method.
4. When the transfer is complete, the client closes the connection by calling the Close method of the socket.

The pseudo code is as follows:

1 Create sockets, then connect to the remote address, socket, connect.

2 Start sending data after the connection is established. Send (data), of course, can read the server from the buffer. RECV (BUFF)

When 3 is complete, close the socket. Close

Cs=socket (Socket.af_inet,socket.sock_dgram)

#创建客户套接字

Cs.connect () #尝试连接服务器

Comm._loop: #通信循环

Cs.send ()/cs.recv () #对话

Cs.close ( ) #关闭套接字

From socket import *;host = ' host IP ' port = 8899bufsiz = 1024addr = (host,port) Tcpclisock = socket (af_inet,sock_stream) tcpcli Sock.connect (addr) while True:    data = raw_input (' > ')    if not data:        break    tcpclisock.send (data)    Data_rec = tcpclisock.recv (bufsiz)    if not data_rec:        break    print Data_rec


<pre name= "code" class= "python" >post = ' 210.25.137.230 ' port = 8899bufsiz = 1024addr = (post,port) Tcpsersock = socket (Af_inet,sock_stream) tcpsersock.bind (addr) Tcpsersock.listen (5) while True:    print ' Wait client Conncet '    Tcpclient,addr =tcpsersock.accept ()    print ' Connect from ', addr while    True:        data = TCPCLIENT.RECV ( BUFSIZ)        If not data:            break        tcpclient.send (' [%s]%s '% (CTime (), data)) #        Tcpclient.close () Tcpsersock.close ()

Python network programming--tcp

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.