To compile a server in python, follow these steps:
The first step is to create a socket object. Call the socket constructor. For example:
Socket = socket. socket (family, type)
The family parameter represents the address family, which can be AF_INET or AF_UNIX. The AF_INET family includes Internet addresses, and the AF_UNIX family is used for communication between processes on the same machine.
The type parameter represents the socket type, which 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 implemented through the bind method of the socket object:
Socket. bind (address)
The address of a socket created by AF_INET must be a dual-element tuple in the format of host and port ). Host indicates the host, and port indicates the port number. If the port is in use, the host name is incorrect, or the port is retained, the bind method will cause a socket. error exception.
Step 3: Use the listen method of socket to receive connection requests.
Socket. listen (backlog)
Backlog specifies the maximum number of customers allowed to connect to the server. The value must be at least 1. After receiving the connection request, these requests need to be queued. If the queue is full, the request is rejected.
Step 4: The server socket waits for the customer to request a connection through the socket accept method.
Connection, address = socket. accept ()
When the accept method is called, the socket enters the "waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is the new socket object, and the server must communicate with the customer through it; the second element address is the customer's Internet address.
- The fifth step is the processing phase. The server and client communicate (transmit data) through the send and recv methods ). The server calls send and uses a string to send messages to the customer. The send method returns the number of sent characters. The server uses the recv method to receive information from the customer. When calling recv, the server must specify an integer, which corresponds to the maximum data volume that can be received through this method call. The recv method enters the "blocked" status when receiving data, and returns a string that indicates the received data. If the amount of data sent exceeds the recv limit, the data will be truncated. The excess data is buffered at the receiving end. When recv is called in the future, excess data will be deleted from the buffer zone (and any other data that the customer may send since the last recv call ).
- When the transmission ends, the server calls the socket close method to close the connection.
Follow these steps to write a client in python:
- Create a socket to connect to the server: socket = socket. socket (family, type)
Use the connect Method of socket to connect to the server. For the AF_INET family, the connection format is as follows:
Socket. connect (host, port ))
Host indicates the server host name or IP address, and port indicates the port number bound to the server process. If the connection is successful, the customer can communicate with the server through the socket. If the connection fails, the socket. error exception will occur.
- In the processing phase, the customer and server will communicate with the recv method through the send method.
- After the transmission ends, the customer calls the close method of socket to close the connection.
The following is a simple example:
Server. py
Python code
Client. py
Python code
Run server. py on the terminal, and then run clien. py. "welcome to server" will be printed on the terminal! ". If you change sock. send ('1') of client. py to another value, "please go out!" will be printed! ", If you change time. sleep (2) to a value greater than 5, the server will time out.
Figure 1 tcp communication Diagram
The tcp communication diagram of a socket. We all know that tcp communication requires three handshakes. Tcp is a reliable, connection-oriented, and best-effort transmission protocol, while udp is an unreliable, non-connection-oriented, and hard-to-transmit protocol. But unreliable does not mean it is useless. udp has its own application scenarios. Almost all speech and video are using the udp Protocol. Its reliability is only relative to tcp, however, its advantage is efficiency, which is more important than reliability in some scenarios. This involves trade-off, that is, trade-offs. You need to weigh the pros and cons based on your application, and then select.
After the socket chooses to initialize a tcp socket, it will bind an address and port, and then start listen. After the client connects to the tcp of the listen, the server will accept the request, then a new socket is generated, and both parties use this new socket (address and port, address or the above listen address, the port will be a new, this can be seen from the printed results) for subsequent communication. The original port will continue with the new listen request.
The following is the tcpServer code.
import socket HOST='192.168.0.37' PORT=50000 BUFFER=4096 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind((HOST,PORT)) sock.listen(0) print('tcpServer listen at: %s:%s\n\r' %(HOST,PORT)) while True: client_sock,client_addr=sock.accept() print('%s:%s connect' %client_addr) while True: recv=client_sock.recv(BUFFER) if not recv: client_sock.close() break print('[Client %s:%s said]:%s' % (client_addr[0],client_addr[1],recv)) client_sock.send('tcpServer has received your message') sock.close()
Socket. SOCK_STREAM is used to specify that the socket is based on the tcp protocol.
The following is the corresponding client code
import socket HOST='192.168.0.37' PORT=50000 BUFFER=4096 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect((HOST,PORT)) sock.send('hello, tcpServer!') recv=sock.recv(BUFFER) print('[tcpServer said]: %s' % recv) sock.close()
The following is the udpServer code.
import socket HOST='192.168.0.37' PORT=50001 BUFFER=4096 sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.bind((HOST,PORT)) #sock.listen(0) print('tcpServer listen at: %s:%s\n\r' %(HOST,PORT)) while True: #client_sock,client_addr=sock.accept() #print('%s:%s connect' %client_addr) while True: recv,client_addr=sock.recvfrom(BUFFER) if not recv: break print('[Client %s:%s said]:%s' % (client_addr[0],client_addr[1],recv)) sock.sendto('tcpServer has received your message',client_addr)
You will find that because udp is non-connected and does not require three-way handshakes, you do not need to perform listen or accept, so you can directly communicate with each other. When initializing the socket
socket.SOCK_DGRAM
To implement the initialization of the socket is based on the udp protocol.
If the udp socket is initialized, no listen or accept is required. You can specify the address and port of the other party when both parties communicate with each other.
Corresponding client code:
#!/usr/bin/env python # -*- coding: UTF-8 -*- import socket HOST='192.168.0.37' PORT=50001 BUFFER=4096 sock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) sock.connect((HOST,PORT)) sock.send('hello, tcpServer!') recv=sock.recv(BUFFER) print('[tcpServer said]: %s' % recv) sock.close()
Server:
[Python] view plaincopyprint?# server import socket address = ('127.0.0.1', 31500) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # s = socket.socket() s.bind(address) s.listen(5) ss, addr = s.accept() print 'got connected from',addr ss.send('byebye') ra = ss.recv(512) print ra ss.close() s.close() Client:[python] view plain copy print ?# client import socket address = ('127.0.0.1', 31500) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(address) data = s.recv(512) print 'the data received is',data s.send('hihi') s.close() Running result:
Server
[Work@db-testing-com06-vm3.db01.baidu.com python] $ python server. py
Got connected from ('2017. 0.0.1 ', 127)
Hihi
Client
[Work@db-testing-com06-vm3.db01.baidu.com python] $ python client. py
The data already ed is byebye
========================================================== ==============================================
References: http://www.cppblog.com/lai3d/archive/2008/02/19/42919.html
A simple example of server-Client Communication
Server:
Importsocket
S = socket. socket ()
S. bind ('xxx. xxx. xxx. XXX', xxxx) # IP address and port number
S. listen (5)
Cs, address = s. accept ()
Print 'gotconnectedfrom ', address
Cs. send ('byebye ')
Ra = cs. recv (512)
Printra
Cs. close ()Client:
Importsocket
S = socket. socket ()
S. connect ('xxx. xxx. xxx. XXX', xxxx) # Same as the IP address and port number of the server program
Data = s. recv (512)
S. send ('hihi ')
S. close ()
Print 'thedatareceivedis ', dataRun:
Test on the local machine (in windows, you can change the ip address to the ip address of the local machine, the port number is above 1024, and windows will retain the ip address below 1024), run -- CMD -- to enter the command line mode
First, the python server program, and then the python client program.
You can also use the telnet IP address and port number after starting the server program.
Allow the server to continuously accept connections
Server. py
Importsocket
S = socket. socket ()
S. bind ('192. 168.43.20.', 192 ))
S. listen (5)
While1:
Cs, address = s. accept ()
Print 'gotconnectedfrom ', address
Cs. send ('helloiamserver, welcome ')
Ra = cs. recv (512)
Printra
Cs. close ()Test whether two sockets exist in one program.
Client. py
Importsocket
S = socket. socket ()
S. connect ('192. 168.43.20.', 192 ))
Data = s. recv (512)
Print 'thedatareceivedis/N', data
S. send ('hihiamclient ')
Sock2 = socket. socket ()
Sock2.connect ('192. 168.43.20.', 192 ))
Data2 = sock2.recv (512)
Print 'thedatareceivedfromserveris/N', data2
Sock2.send ('clientsendusesock2 ')
Sock2.close ()
S. close ()