Python Network programming

Source: Internet
Author: User

Thanks to?http://www.liaoxuefeng.com

Various protocols in the network

1. IP protocol: The IP protocol is an important network protocol that corresponds to the unique identity of each computer: the IP address, which is actually the interface of each calculator link network, usually the NIC. The IP protocol is responsible for transmitting data from one computer to another computer, the data is divided into small pieces, and then through the IP packet (IP packet contains data, source IP address and destination IP address, source port and destination port), through the connection between two computers to send out the line, However, the IP protocol does not guarantee that the data arrives accurately and does not guarantee sequential arrival.

2. TCP protocol: The TCP protocol is based on the IP protocol, the two computers through the handshake, establish a reliable connection, and the number of each IP packet, to ensure that the data order reliable arrival, if a packet loss occurs, the automatic re-send. On the basis of the TCP protocol, there are more advanced protocols: HTTP, SMTP and other common protocols.

3. UDP protocol: UDP protocol does not need to establish a reliable connection, directly send packets, but does not guarantee that accurate arrival. The advantage of the UDP protocol is that it is fast and can use the UDP protocol in some data that is not required to be reliably reached.

TCP Client Programming

The basis for establishing a network connection is to create a socket,socket that specifies the IP address and port number of the destination computer, as well as the protocol type.

To initiate a TCP connection on the client, you need to specify the socket protocol as the TCP/IP protocol:

Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM)?

When the socket class is instantiated, it accepts 4 parameters: Family=af_inet,type=sock_stream,proto=0,_sock=none

The fourth parameter, _sock, is a _realsocket object that, if specified, inherits the family, type, photo property from the object, and inherits the delegate method: ("recv", "Recvfrom", "Recv_into" , "Recvfrom_into", "Send", "SendTo"). The _realsocket class is implemented in C, so you can only see the header file _realsocket.py.

The first three parameters are: address protocol, stream Protocol, interface protocol (? )

After the socket object has been created, the connection is established through the Connet method:

S.connet ((' www.baidu.com '), 80)

The Connet method requires an address to be passed in, and if it is a socket for the IP class, it needs to pass in a tuple containing the address (which will be resolved by DNS) and the port

Once the connection is established, the request can be sent. The TCP protocol is a two-way connection, both parties can send data, but the specific sending rules have a higher level of protocol, such as the HTTP Protocol decision (HTTP protocol rule: must have a client to send a request to the server, the server received before sending data to the client):

S.send (' get/http/1.1\r\nhost:www.baidu.com\r\nconnection:close\r\n\r\n ')

If you send an HTTP 1.1 protocol request, get Baidu home page content, after the request sent, Baidu Server will respond to the request, and send us the contents of the home page, through the Recv method to receive the information sent by the server, and specify the maximum number of bytes Received:

Buffer = []
While True:
? ?? D = S.RECV (1024)
? ? If D:
? ? ? ? Buffer.append (d)
? ? Else
? ? ? ? Break
data = '. Join (buffer)

As the above data contains all the information received from the server, including an HTTP header, and the real need to receive the Web page itself, and then send the request, we take two carriage return to break the HTTP header and received the page, so it is new separation can get Baidu home content:

Header, html = data.split (' \r\n\r\n ', 1)

Write it to a file:

With open (' baidu.html ', ' WB ') as F:
? ? F.write (HTML)

Open baidu.html with the browser, you can see the contents of the homepage of Baidu

The total script is as follows:

__author__ = ' Liangzb '
Import socket
s = Socket.socket (family=2,type=socket. SOCK_STREAM)
Print type (s.family)
S2 = Socket.socket (_sock=s)
Print s2.family
S.connect (' www.baidu.com ', 80)
S.send (' get/http/1.1\r\nhost:www.baidu.com\r\nconnection:close\r\n\r\n ')
Buffer = []
While True:
? ? D = S.RECV (1024)
? ? If D:
? ? ? ? Buffer.append (d)
? ? Else
? ? ? ? Breakdata = '. Join (buffer)
S.close ()
# Print Data
Header, html = data.split (' \r\n\r\n ', 1)
# Print Header
With open (' baidu.html ', ' W ') as F:
? ? F.write (HTML)

TCP Server-side programming

The difference between a server and a client is that the server needs to accept requests from different clients and respond separately, in order to implement the process, you first need to establish a binding that binds the server's IP address and port:

S.bind (' 127.0.0.1 ', 9999)

After that, the listen method is called to listen for messages from that port, and the incoming parameter specifies the maximum number of pending connections:

Listen (max_connection)

Next, the server should remain running, enable a dead loop to receive connections from the client, accept the connection from the client, and return the client's socket object and address. It should be noted that for each request, a new thread or process should be opened (win can only open threads) to handle:

While True:
? ? Sock, addr = S.accept ()
? ? t = Threading. Thread (Target=tcplink, args= (sock, addr))
? ? T.start ()

Write a handler function to respond to the request:

def tcplink (sock, addr):
? ? print ' Accept new connection from%s:%s ... '% addr
? ? Sock.send (' welcome! ')
? ? While True:
? ? ? ? data = SOCK.RECV (1024)
? ? ? ? Time.sleep (1)
? ? ? ? if data = = ' exit ' or not data:
? ? ? ? ? ? Break
? ? ? ? Sock.send (' Hello,%s! '% data)
? ? Sock.close ()
? ? print ' Connection from%s:%s closed. '% addr

The server-side total script is as follows:

__author__ = ' Liangzb '
Import threading
Import socket
Import time

def tcplink (sock, addr):
? ? print ' Accept new connection from%s:%s ... '% addr
? ? Sock.send (' welcome! ')
? ? While True:
? ? ? ? data = SOCK.RECV (1024)
? ? ? ? Time.sleep (1)
? ? ? ? if data = = ' exit ' or not data:
? ? ? ? ? ? Break
? ? ? ? Sock.send (' Hello,%s! '% data)
? ? Sock.close ()
? ? print ' Connection from%s:%s closed. '% addr

s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind (' 127.0.0.1 ', 9999)
S.listen (5)
print ' Waiting for connection ... '

While True:
? ? Sock, addr = S.accept ()
? ? t = Threading. Thread (Target=tcplink, args= (sock, addr))
? ? T.start ()

Can be tested by another client to send a message to the server, note that the IP address binding here is 127.0.0.1, is a local address, can only be native access

Client program Reference:

Import socket
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.connect (' 127.0.0.1 ', 9999)
Print S.RECV (1024)
For data in [' Michael ', ' Tracy ', ' Sarah ']:
? ? S.send (data)
? ? Print S.RECV (1024)
S.send (' exit ')
S.close ()

Source code from: http://www.liaoxuefeng.com/, thanks to Liaoxuefeng for share

Operating effect:

UDP programming

The protocol is not deterministic for connection reliability, the socket stream protocol should be set to: Sock_dgram:

s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)

Due to the characteristics of the UDP protocol, the service side of UDP does not need to call the Listen method when establishing a connection, but instead responds directly to the received request, while the client's information is recvfrom by the tuple returned by the method. When sending a message, it is only necessary to pass the client's address as the second parameter through the SendTo method.

But in the UDP protocol client, also does not need to pass through the connection first, but sends the prepared request to one address directly, uses the SendTo method, passes the service side's address as the second parameter, the other receives the method and the TCP same.

Python Network 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.