1. Socket base
There are two ways to connect the client and the server: TCP and UDP,TCP are connection-oriented (three handshake, four wave, etc.), reliable but resource-consuming, but UDP is not connected, unreliable but fast. There's a lot of learning, but most people know that's enough.
2. A simple TCP example (blocking mode)
In both Python and other languages, socket programming has almost a fixed template, and here's a simple example for calculating factorial and, for example, sending 5 to the client, and returning 5!+4!+3!+2!+1! to the server side.
Server-side Python code:
Import socket
sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
sock.bind ((' localhost ', 21567))
Sock.listen (1) while
True:
print ' Waiting for Connecting ... '
connection,address = sock.accept ()
print ' ... connected from:%s:%i '% (address[0],address[1)) While
True:
data = CONNECTION.RECV (1024)
if not data: Break result
= 0 for
i in range (1,int (data) +1: Result
= result + reduce (lambda x,y:x*y,range (1,i+1))
connection.send (' The result is%i '%result) C16/>connection.close ()
sock.close ()
The following is an explanation of the code:
First, instantiating a socket object requires three parameters, the first is the address family (typically Af_inet), the second parameter specifies the connection mode (Sock_stream represents the TCP mode, the SOCK_DGRAM represents the UDP), and the third parameter defines the protocol used.
Then, bind the IP address and port, turn on listening, and set the queue length to wait for the connection.
Server-side is to use the Accept () method to accept the client, blocking mode, that is, how to not connect to the client, will be blocked waiting.
Once a client request is received, the data can be accepted with the recv () method, processed, and then sent back to the client using the Send () method.
Client-side Python code:
Import socket
sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
sock.connect ((' localhost ', 21567))
data = ' 5 '
sock.send (data)
Receiveddata = Sock.recv (1024)
Print Receiveddata
sock.close ()
Client code is very simple, first of all, instantiate a socket object, and then establish a connection with the server side, send data, accept server-side returned data