Week 8 of Python learning from scratch: socket and python week 8

Source: Internet
Author: User

Week 8 of Python learning from scratch: socket and python week 8
Socket network programming 1, Socket programming (1) Socket Method Introduction

  • Socket is an abstract concept of network programming. Generally, we use a Socket to indicate "open a network link". To open a Socket, we need to know the IP address and port number of the target computer, and then specify the protocol type.
  • A socket is the endpoint of a two-way communication channel. The socket may be in the communication process, process on the same machine, or process between different computers
  • To create a Socket, you must use the socket. socket () method of the Socket module.
  • General syntax in the socket module:

S = socket. socket (socket_family, socket_type, protocol = 0)

(3) Introduction to TCP
  • Most connections are reliable TCP connections. When creating a TCP connection, the client actively initiates the connection and the server passively responds to the connection
  • For example, when accessing Sina in a browser, our computer is the client, and the browser will initiate a connection to the Sina server. If everything goes well, the Sina Server accepts our connection, and a TCP connection is established, and the subsequent communication is to send the webpage content.
(4) TCP programming demonstration-Client
  • To create a Socket based on TCP connection, the Code is as follows:
1 import socket2 3 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)4 s.connect(('www.sina.com.cn',80))

 

  • After a TCP connection is established, you can send a request to the server, requesting that the content of the homepage be returned. The sent text format must comply with the HTTP standard, then receiving the data returned by the server, and closing the connection.
(5) TCP programming demonstration-Server
  • Server programming is more complex than client programming. server processes must first bind a port and listen to connections from other clients. If a client is connected, the server establishes a Socket connection with the client, and the subsequent communication relies on the Socket connection.
  • Write a simple server program that receives client connections and adds "Hello" to the string sent from the client to send it back. The Code is as follows:
1 import socket 2 3 Host = 'locakhost' # Listening IP address 4 port = 8888 # listening port 5 s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # establish socket 6 s. bind (Host, port) # bind the IP address and port 7 s. listen (5) # Start listening to 8 conn, addr = s. accept () # accept a new connection 9 data = conn. recv (1024) # receive client string 10 conn. sendall (data + 'hello') # Send a string to the client

 

  • Note that after a Socket is bound to the same port, it cannot be bound to another Socket.
(6) Introduction to UDP
  • TCP establishes a reliable connection, and both parties can send data in the form of a stream. Compared with TCP, UDP is a connectionless protocol.
  • When using UDP, you do not need to establish a connection. You only need to know the IP address and port number of the other party to send data packets directly. However, it is unclear whether it can be reached.
  • Although UDP is not reliable in data transmission, its advantage is that it is faster than TCP. For data that does not require reliable arrival, you can use the UDP protocol.
(7) UDP programming demonstration
  • Transmit data over UDP. Similar to TCP, UDP communication can be divided into clients and servers. The server must first bind a port. The Code is as follows:
1 s = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) 2 s. bind ('192. 0.0.1 ', 127) # port binding

 

  • When the client uses UDP, it still creates a UDP-based Socket, but it does not need to call connect () and sends data directly to the server through sendto (). The Code is demonstrated:
1 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)2 for data in ['Michael','Tracy','Sarah']:3     s.sendto(data)

 

  • Note that the UDP port and TCP port bound to the server do not conflict with each other. UDP port 9999 and TCP port 9999 can be bound to each other.
2. TCP programming example

Socket is an abstract concept of network programming. Generally, we use a Socket to indicate "open a network link". To open a Socket, we need to know the IP address and port number of the target computer, and then specify the protocol type.

  • Client

For example, when we access Sina in a browser, our computer is the client, and the browser will initiate a link to the Sina server. If everything goes well, the Sina server receives our connection, and a TCP connection is established, and the subsequent communication is to send webpage content.

Therefore, we need to create a Socket based on TCP connection. We can do this:

1 # import socket library 2 import socket3 # create a socket: 4 s = socket. socket (socket. AF_INET, socket. SOCK_STREAM) 5 # establish a connection 6 s. connect ('www .sina.com.cn ', 80 ))

When creating a Socket, AF_INET specifies that the IPv4 protocol is used. If you want to use more advanced IPv6, AF_INET6 is specified. SOCK_STREAM specifies the stream-oriented TCP protocol. In this way, a Socket object is created successfully, but no connection has been established.

To actively initiate a TCP connection, the client must know the IP address and port number of the server. The IP address of the Sina website can be automatically converted to the IP address using the domain name www.sina.com.cn, and the standard port 80 of the Web service.

Therefore, the code for connecting to the Sina server is as follows:

s = connect(('www.sina.com.cn',80))

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

After a TCP connection is established, we can send a request to the Sina server, requesting that the content of the homepage be returned:

# Send data: s. send ('get/HTTP/1.1 \ r \ nHost: www.sina.com.cn \ r \ nConnection: close \ r \ n \ r \ n ')

 

A two-way channel is created for a TCP connection. Both parties can send data to the other party at the same time. However, the coordination depends on the specific protocol. For example, the HTTP protocol requires the client to send a request to the server before sending data to the client.

The text format sent must comply with the HTTP standard. If the format is correct, you can then receive the data returned by the Sina Server:

1 # receive data: 2 buffer = [] 3 while True: 4 # Each time a maximum of 1 K bytes are received: 5 d = s. recv (1024) 6 if d: 7 buffer. append (d) 8 else: 9 break10 data = ''. join (buffer)

 

When receiving data, call the recv (max) method to receive a maximum of specified bytes at a time. Therefore, it is repeatedly received in a while loop until recv () returns NULL data, indicates that the receiving is complete and the loop is exited.

After receiving the data, call the close () method to close the Socket. In this way, a complete network communication is over:

# Close connection s. close ()

 

The received data includes the HTTP header and the webpage itself. We only need to separate the HTTP header from the webpage, print the HTTP header, and save the webpage content to the file:

Header, html = data. split ('\ r \ n \ r \ n', 1) print header # Write the received data to the file: with open('sina.html', 'wb ') as f: f. write (html)

 

 

Now, just open the sina.html file in the browser and you will be able to see the Sina homepage.

  • Server

Server programming is more complex than client programming.

The server process must first bind a port and listen for connections from other clients. If a client is connected, the server establishes a Socket connection with the client, and the subsequent communication relies on the Socket connection.

Therefore, the server opens a fixed port (such as 80) listener. This Socket connection is created every time a client connects. Because the Server opens a fixed port (such as 80) listener, this Socket connection is created every time a client connects. Because the server has a large number of connections from the client, the server must be able to distinguish the client to which a Socket connection is bound. A Socket depends on four items: server address, server port, client address, and client port to uniquely identify a Socket.

However, the server also needs to respond to multiple client requests at the same time. Therefore, each connection requires a new process or thread for processing. Otherwise, the server can only serve one client at a time.

Let's write a simple server program that receives client connections and adds Hello to the string sent from the client and then sends it back.

First, create a Socket based on IPv4 and TCP Protocols:

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

 

Then, we need to bind the listening address and port. The server may have multiple NICs, which can be bound to the IP address of a network adapter, 0.0.0.0 to all network addresses, and 127.0.0.1 to the local address. 127.0.0.1 is a special IP address, indicating the address of the Local Machine. If it is bound to this address, the client must run on the local machine at the same time to connect. That is to say, external computers cannot connect in.

The port number must be specified in advance. Because the service we wrote is not a standard service, we use the port number 9999. Note that the port number smaller than 1024 must have administrator permissions to bind:

# Listening port s. bind ('127. 0.0.1 ', 127 ))

 

Then, call the listen () method to start listening to the port. The input parameters specify the maximum number of pending connections:

s.listen(5)print 'Waiting for connection...'

 

Next, the server program accepts connections from the client through a permanent loop. accept () will wait and return a client connection:

While TAG: # accept a new connection conn, addr = s. accept () # create a new thread to process TCP connections t = threading. thread (target = tcplink, args = (conn, addr) t. start ()

 

Each connection must be processed by creating a new thread (or process). Otherwise, a single thread cannot accept connections from other clients during connection processing:

def tcplink(conn,addr):    print ('Accept new connection form {0}'.format(addr))    conn.send('Welcome!')    while True:        data = conn.recv(1024)        time.sleep(1)        if data == 'exit' or not data:            break        socket.send('Hello,{0}!'.format(data))    conn.close()    print ('Connection from {0} closed.'.format(addr))

 

After the connection is established, the server sends a welcome message, waits for the client data, and adds Hello to send it to the client. If the client sends an exit string, close the connection directly.

To test this server program, we also need to write a client program:

  

S = socket. socket (socket. AF_INET, socket. SOCK_STREAM) # establish a connection: s. connect ('2017. 0.0.1 ', 9999) # receive the welcome message: print s. recv (1024) for data in ['Michael ', 'tracy', 'Sarah ']: # send data: s. send (data) print s. recv (1024) s. send ('exit ') s. close ()

 

Then we open two command line windows, one running the server program and the other running the client program to see the effect.

It should be noted that the client will exit after running the program, and the server program will run forever. You must press Ctrl + C to exit the program.

  • Summary

Using the TCP protocol for Socket programming is very simple in Python. for the client, you must actively connect to the server's IP address and the specified port. For the server, you must first listen to the port, and then, create a thread or process to process each new connection. Generally, server programs run infinitely.

After a Socket is bound to the same port, it cannot be bound to another Socket.

 

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.