TCP Mode server side
The server-side socket general process is this:
- Create a socket (you can choose the socket type Inet,unix, etc., and the connection mode TCP/UDP)
- Use bind to expose a port so that the client can easily connect
- Set the size of a listen queue
- Enter an infinite loop in which the Accept function is used to wait for the client to connect, and this function returns a new socket that corresponds to the client's socket and establishes a communication channel. The processing of sockets is generally placed in a separate external function (concurrency)
- Read and write to the socket via send ()/RECV ()
Example:
1 deftcpserver ():2Srvsock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)3Srvsock.bind (("', 9527)) 4Srvsock.listen (5) 5 6 whileTrue:7Clisock, (remotehost, remoteport) =srvsock.accept ()8 Print "[%s:%s] Connected"%(RemoteHost, RemotePort)9 #Do something on the clisockTen clisock.close () One A - if __name__=="__main__": -TCPServer ()Client Side
- Create a new socket
- Using the Connect function to get a connection to a remote host
- I/O operation on this socket
Instance:
1 deftcpClient ():2Clisock =Socket.socket (socket.af_inet, socket. SOCK_STREAM)3Clisock.connect (('localhost', 9527)) 4 5 #I/O on this clisock6 #clisock.send ("")7 #dat = clisock.recv (len)8 9 PrintdatTen One if __name__=="__main__": ATcpClient ()UDP mode
UDP known as no connection transmission, there is no TCP so complex, three times handshake, error retransmission and other mechanisms are not, hair, just send, collect, receive it? Do not know, the order is not what to do? No matter! That's it, but the speed is much higher than TCP. In places where the data frame requirements are not very high, this is really useful, such as video transmission on the network, audio transmission and so on.
Server Side
- Set up a socket in the form of a datagram
- Exposes a port while the client is connected
- Start receiving data
Instance:
1 defudpserver ():2Address = ("', 9527) 3Srvsock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)4 Srvsock.bind (address)5 #data,addr = Srvsock.recvfrom (2048)6 7 if __name__=="__main__": 8Udpserver ()
It is important to note that the quotation marks in the address tuple in the server indicate that a datagram can be accepted for any address, and the TCP example indicates that a connection originating at any address can be accepted.
Client Side
- Create a new datagram socket
- Send and receive data
Instance:
1 defudpclient ():2Address = ('localhost', 9527) 3Clisock =Socket.socket (socket.af_inet, socket. SOCK_DGRAM)4 #clisock.sendto (data, address)5 6 if __name__=="__main__": 7UdpClient ()
Python Network programming