Python socket network programming steps of the use of socket socket

  • 2020-04-02 13:18:29
  • OfStack

One, socket
A socket is an object that provides the current portable standard for network application providers on a particular network protocol suite (such as TCP/IP, ICMP/IP, UDP/IP, etc.). They allow programs to accept and make connections, such as sending and receiving data. In order to establish communication channels, it is important that each endpoint of network communication have a socket object.
Sockets are part of the core of BSD UNIX systems, and they are adopted by many other unix-like operating systems, including Linux. Many non-bsd UNIX systems (such as ms-dos, Windows, OS /2, MAC OS, and most host environments) provide socket support in the form of libraries.
The three most popular socket types are stream,datagram, and raw. The stream and datagram sockets interface directly to the TCP protocol, while the raw socket interfaces to the IP protocol. But sockets are not limited to TCP/IP.

Socket module

The socket module is a very simple object-based interface that provides access to the low-level BSD socket style network. Client and server sockets can be implemented using this module. To build a simple server in python with TCP and streaming sockets, you need to use the socket module. The module contains functions and class definitions to generate programs that communicate over the network. In general, there are six steps to establish a server connection.

The first step is to create the socket object. Call the socket constructor.

Socket = socket. The socket (familly, type)
The value of family can be AF_UNIX(Unix domain for inter-process communication on the same machine), AF_INET (TCP and UDP for the IPV4 protocol), as for the type parameter, SOCK_STREAM (stream socket), or SOCK_DGRAM (datagram socket), and SOCK_RAW (raw socket).

The second step is to bind(assign) the socket to the specified address, socket.bind(address)

The address must be a two-element tuple ((host,port)), hostname, or IP address + port number. If the port number is being used or retained, or the hostname or IP address is wrong, a socke.error exception is thrown.

Step 3: after binding, the socket must be ready to accept the connection request.

Socket. Listen (backlog)
The backlog specifies a maximum number of connections, at least 1, that must be queued when connection requests are received and rejected if the queue is full.

Step 4. The server socket waits for a client to request a connection through the socket's accept method:
Connection, address = socket. The accept ()
When the accept method is called, the socket enters a state of 'waiting' (or blocking). When the client requests a connection, the method establishes the connection and returns to the server. The accept method returns a tuple with two elements, as in connection,address. The first element (connection) is the new socket object through which the server communicates with the client. The second element (address) is the customer's Internet address.

Step 5 is the processing phase, in which the server and client communicate via the send and recv methods. The server calls send and sends the information to the customer as a string. The send method returns the number of characters sent. The server receives information from the client using the recv method. When recv is called, you must specify an integer to control the maximum amount of data accepted for the call. The recv method enters the 'blocket' state when it accepts data and returns a string to represent the received data. If more is sent than recv allows, the data is truncated. Excess data is cached on the receiving end. When recv is called later, the excess data is removed from the buffer.

Step 6, the transfer ends, and the server calls the socket close method to close the connection.

Establishing a simple customer connection takes four steps.

Step 1: create a socket to connect to the server socket=socket.socket(family,type)
Step 2: use the socket's connect method to connect to the server socket.connect((host,port))
In step 3, the client and server communicate through the send and recv methods.
Step 4. When finished, the client closes the connection by calling the socket's close method.


Steps to write server in python:

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 and can be 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 the socket type and can be SOCK_STREAM(stream socket) and SOCK_DGRAM(datagram socket).

The second step is to bind the socket to the specified address. This is achieved through the socket object's bind method:
Socket. The bind (address)
Socket created by AF_INET. The address address must be a two-element tuple in the format (host, port). Host represents the host and port represents the port number. The bind method throws a socket.error exception if the port number is in use, the hostname is incorrect, or the port is retained.

The third step is to receive the connection request using the listen method of the socket socket.
Socket. Listen (backlog)
Backlog specifies how many customers are allowed to connect to the server at most. It has a value of at least 1. When connection requests are received, they are queued and rejected if the queue is full.

The fourth step is for the server socket to wait for the client to request a connection through the socket's accept method.
Connection, address = socket. The accept ()
When the accept method is called, the socket enters a "waiting" state. When the client requests a connection, the method establishes the connection and returns to the server. The accept method returns a tuple (connection,address) with two elements. The first element, connection, is a new socket object through which the server must communicate with the client. The second element, address, is the customer's Internet address.

The fifth step is the processing phase, in which the server and client communicate via the send and recv methods. The server calls send and sends the information to the customer as a string. The send method returns the number of characters sent. The server receives information from the client using the recv method. When recv is called, the server must specify an integer corresponding to the maximum amount of data that can be received through this method call. The recv method enters a "blocked" state when receiving data, and finally returns a string of characters to represent the received data. If more data is sent than is allowed by recv, the data is truncated. Excess data is cached at the receiving end. When recv is called later, the excess data is removed from the buffer (and any other data that the customer may have sent since recv was last called).
When the transfer ends, the server calls the socket's close method to close the connection.


Steps to write client in python:

Create a socket to connect to the server: socket = socket.socket(family, type)
Connect to the server using the socket's connect method. For the AF_INET family, the connection format is as follows:
Socket. Connect ((host, port)
Host represents the hostname or IP of the server, and port represents the port number to which the server process is bound. If the connection is successful, the client can communicate with the server through the socket. If the connection fails, a socket.error exception will be raised.
During the processing phase, the client and server will communicate via the send and recv methods.
At the end of the transmission, the client closes the connection by calling the socket's close method.

Here's a simple example:

Server. Py


if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8001))
sock.listen(5)
while True:
connection,address = sock.accept()
try:
connection.settimeout(5)
buf = connection.recv(1024)
if buf == '1':
connection.send('welcome to server!')
else:
connection.send('please go out!')
except socket.timeout:
print 'time out'
connection.close()


Client. Py

if __name__ == '__main__':
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8001))
import time
time.sleep(2)
sock.send('1')
print sock.recv(1024)
sock.close()

Running server.py on the terminal, then running clien.py, will print "welcome to server!" on the terminal. . If you change the client. Py's sock. Send ('1') to some other value at the terminal it will print "please go out! ", change time.sleep(2) to a value greater than 5, and the server will time out.

For example:
Server:


#socket server end 
# To obtain socket Structure and constants 
from socket import *
#'' The representative server is localhost
myHost = ''
# Listen on a non-reserved port number 
myPort = 50007
# Set up a TCP socket object 
sockobj = socket(AF_INET, SOCK_STREAM)
# Bind it to the port number 
sockobj.bind((myHost, myPort))
# Monitor, allow 5 A link 
sockobj.listen(5)
# Do not end the loop until the process is finished 
while True:
    # Wait for the next client connection 
    connection, address = sockobj.accept( )
    # The link is a new one socket
    print 'Server connected by', address
    while True:
        # Reads the next line of the client socket 
        data = connection.recv(1024)
        # If there is no quantity, break out of the loop 
        if not data: break
        # Send a reply to the client 
        connection.send('Echo=>' + data)
    # when socket closed eof
    connection.close( )

Client:


import sys
from socket import *
serverHost = 'localhost'
serverPort = 50007
# The default text is sent to the server 
message = ['Hello network world']
# If the parameter is greater than 1 The linked server is the first parameter 
if len(sys.argv) > 1:
    serverHost = sys.argv[1]
    # If the parameter is greater than 2 Then, the text of the link is the second parameter 
    if len(sys.argv) > 2:
        message = sys.argv[2:]
# To establish a tcp/ip Socket object 
sockobj = socket(AF_INET, SOCK_STREAM)
# Connect to server and port 
sockobj.connect((serverHost, serverPort))
for line in message:
    # Send by word through the set line To the server 
    sockobj.send(line)
    # The data received from the server is capped at 1k
    data = sockobj.recv(1024)
    # Make sure he's quoting. Yes 'x'
    print 'Client received:', repr(data)
# Close the socket 
sockobj.close( )


Related articles: