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:
= Socket.socket (socket.af_inet, socket. SOCK_STREAM) # Establish connection: S.connect (('www.sina.com.cn')
Socketwhen created, AF_INET specifies that the IPV4 protocol is used, and if a more advanced IPv6 is used, it is specified as AF_INET6 . SOCK_STREAMspecifies that a stream-oriented TCP protocol is used so that an Socket object is created successfully, but no connection has been established.
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?
The answer is that the port number must be fixed as a server and what services are provided. 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.
So our code to connect to the Sina server is as follows:
S.connect ('www.sina.com.cn')
Note The parameter is one tuple 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 ')
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:
= [] while True: # receives up to 1k bytes at a time:= S.recv (1024x768) if d: buffer.append (d) Else: break= b' . Join (buffer)
When the data is received, the method is called to recv(max) 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 socket so that a complete network communication is over:
# 关闭连接: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) print (Header.decode (' utf-8') # writes the received data to a file: with open ('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
Server programming is a bit more complicated than client programming.
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:
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
Then we want to bind the listening address and port. The server may have more than one network card, can be bound to the IP address of a network card, can also be 0.0.0.0 bound to all network addresses, can also be used 127.0.0.1 to bind to the native address. 127.0.0.1is a special IP address that represents the native address, if bound to this address, the client must be running at the same time in order to connect, that is, the external computer cannot connect in.
The port number needs to be specified beforehand. Because we write this service is not a standard service, so use 9999 this port number. Note that the less-than 1024 port number must have administrator privileges to bind:
# Listening Port: S.bind ('127.0.0.1'9999)
Immediately thereafter, the calling listen() method starts listening on the port, and the incoming parameter specifies the maximum number of waiting connections:
S.listen (5) print ('waiting for connection ... ')
Next, the server program receives a connection from the client through a permanent loop that accept() waits for and returns a client connection:
while True: # accepts a new connection: = s.accept () # Creates a new thread to handle the TCP connection:= Threading. Thread (Target=tcplink, args=(sock, addr)) T.start ()
Each connection must create a new thread (or process) to handle, or the single thread cannot accept connections from other clients during the process of processing the connection:
def tcplink (sock, addr): Print ('Accept New connection from%s:%s ...'%addr) sock.send (b'welcome!') whileTrue:data= Sock.recv (1024x768) Time.sleep (1) ifNot data or Data.decode ('Utf-8') =='Exit': BreakSock.send (('Hello,%s!.'% Data.decode ('Utf-8'). Encode ('Utf-8') ) Sock.close () print ('Connection from%s:%s closed.'% addr)
After the connection is established, the server first sends a welcome message, then waits for the client data, plus sends it back to the Hello client. If the client sends a exit string, the connection is closed directly.
To test this server program, we also need to write a client program:
s =Socket.socket (socket.af_inet, socket. SOCK_STREAM) # Establish connection: S.connect (('127.0.0.1',9999) # Receive Welcome message: Print (S.RECV (1024x768). Decode ('Utf-8')) forDatainch[b'Michael'B'Tracy'B'Sarah']: # Send data: s.send (data) print (S.RECV (1024x768). Decode ('Utf-8')) S.send (b'Exit') S.close ()
We need to open two command-line windows, one running the server program, the other running the client program, you can see the effect:
Note that the client program runs out, and the server program will run forever, you must press CTRL + C to exit the program.
Summary
Socket programming with the TCP protocol is very simple in Python, for the client, to actively connect to the server's IP and the specified port, for the server, to first listen to the specified port, and then, for each new connection, create a thread or process to process. Typically, the server program will run indefinitely.
The same port, after being bound by a socket, cannot be bound by another socket.
54 Network Programming TCP Programming