Python Learning Notes (45) network Programming (1) TCP programming

Source: Internet
Author: User
Tags server port

Excerpt: Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001432004374523e495f640612f4b08975398796939ec3c000

Sockets are an abstract concept of network programming. Usually we use a socket to indicate "open a network link", while opening a socket needs to know the destination computer's IP address and port number , and then specify the protocol type .

Client

Most connections are reliable TCP connections . When you create a TCP connection, you initiate a connected call to the client , and the passive response is called the server.

For example, when we visit Sina in a browser, our own computer is the client, and the browser initiates a connection to Sina's server. If all goes well, Sina's server accepts our connection, a TCP connection is built up, and the subsequent communication is to send the Web content.

So, we're going to create a TCP connection-based socket that can do this:

# To Import the socket library: Import Socket #  s =#  connection established:s.connect ('www.sina.com.cn' , 80))

When Socket created, AF_INET specifies that the IPv4 protocol is used, and if a more advanced IPv6is used AF_INET6 , it is specified as. Specifies that a stream-oriented TCP protocol is used so that an object is created successfully, but no connection has been established. SOCK_STREAM Socket

To proactively initiate a TCP connection, the client must know the IP address and port number of the server. The IP address of Sina website can be www.sina.com.cn converted to IP address automatically with domain name , but how to know the port number of Sina server?

as a server , the port number must be fixed to provide what kind of service. Because we want to access the Web page, the server that Sina provides Web services must pin the port number to the 80 ports , because the 80 port is the standard port of the Web service . Other services have a corresponding standard port number, such as the SMTP service is a port, the 25 FTP service is a 21 port , and so on. Port number less than 1024 is the Internet standard service ports, the port number is greater than 1024, can be used arbitrarily.

The code to connect to the Sina server is as follows:

S.connect ('www.sina.com.cn', 80)

Note The parameter is tuple one that contains the address and port number .

After establishing the TCP connection, we can send a request to the Sina server and ask to return the contents of the homepage:

# Send data:s.send (b'get/http/1.1\r\nhost:www.sina.com.cn\r\nconnection:close\r\n\r\n' )

(\ r \ n: Carriage return line)

A TCP connection creates a bidirectional channel in which both parties can send data to each other. However, who first sent after the hair, how to coordinate, according to the specific agreement to decide. For example, the HTTP protocol specifies that the client must send a request to the server before the server sends the data to the client.

send the text format must conform to the HTTP standard , if the format is not a problem, then you can receive the data returned by Sina server:

  #   Receive data  buffer = []  while   #   receive up to 1k bytes at a time:  d = S.RECV (10 24)   D : Buffer.append (d)  else  : break  data  = b . Join (buffer)   

When the data is received recv(max) , the method is called to receive a specified number of bytes at a time, so it is received repeatedly in a while loop until the recv() empty data is returned, indicating that the receive is complete and exits the loop.

When we have finished receiving the data, we call the close() method to close the socketso that a complete network communication is over:

# Close connection:S.close ()

The data received include the HTTP header and the Web page itself , we just need to separate the HTTP header and Web page, the HTTP header print out , the content of the Web page to save to the file :

Header, html = data.split (b'\r\n\r\n', 1)      # 1 is the meaning of the split once print( Header.decode ('utf-8')#  writes the received data to a file: withopen ( ' sina.html ' ' WB ' ) as F:    f.write (HTML)

Now, just open the file in the browser sina.html , you can see the homepage of Sina.

Server

The server process first binds a port and listens for connections from other clients. If a client connects, the server establishes a socket connection to the client, and the subsequent communication is connected to the socket.

Therefore, the server opens a fixed port (for example, 80) to listen, creating the socket connection for each client connection. Because the server will have a large number of connections from the client, the server is able to differentiate between which client and which clients the socket connection is bound to. A socket relies on 4 items: server address, server port, client address, client port to uniquely identify a socket.

However, the server also needs to respond to requests from multiple clients at the same time, so each connection requires a new process or a new thread to handle, otherwise the server can only serve one client at a time.

Let's write a simple server program that receives the client connection and sends back the string that the client sent over Hello .

First, create a socket based on the IPV4 and TCP protocol:

Python Learning Notes (45) network Programming (1) TCP 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.