The socket originated from UNIX's "All Borrowed files" idea, in short, similar to file: open-read-write-close operation, file for the operation with the files, the socket for the server and the client operation. Communication based on the network, it is inevitable to escape all kinds of network protocols, in order to quickly develop, in the application layer and the transport layer to join the socket layer, so that TCP (UDP) protocol encapsulation, easy to develop.
First, write a simple socket-based network communication
1 #Import Socket2 fromSocketImport*3Ip_port= ('127.0.0.1', 8080)4Back_log=55buffer_size=10246 7Tcp_client=socket (af_inet,sock_stream)8 Tcp_client.connect (Ip_port)9 Ten whileTrue: OneMsg=input ('>>:'). Strip () A if notMsgContinue -Tcp_client.send (Msg.encode ('Utf-8')) - Print('The client has sent a message') theData=tcp_client.recv (buffer_size) - Print('receive messages from the service side', Data.decode ('Utf-8')) - -Tcp_client.close ()
#Import Socket fromSocketImport*Ip_port=('127.0.0.1', 8080) Back_log=5buffer_size=1024Tcp_server=socket (af_inet,sock_stream) tcp_server.bind (ip_port) Tcp_server.listen (back_log) whileTrue:Print('the server started running') conn,addr=tcp_server.accept ()#service-side blocking Print('Two-way links are', conn)Print('Client Address', addr) whileTrue:#Try:Data=conn.recv (buffer_size)Print('the message sent by the client is', Data.decode ('Utf-8')) Conn.send (Data.upper () )#except Exception: # Breakconn.close () tcp_server.close ( )
The server-side initializes the Socket, then binds to the port (BIND), listens to the port (listen), calls the accept block, waits for the client to connect. At this point if a client initializes a Socket and then connects to the server (connect), the client-server connection is established if the connection is successful. The client sends the data request, the server receives the request and processes the request, then sends the response data to the client, the client reads the data, closes the connection, and ends the interaction at the end.
There are several methods commonly used in sockets:
Socket.socket (): Establishes a socker socket, two parameters, family represents the family. Type is the default TCP
Socket.bind (): Server side, accepted parameters are tuples, not passed host,port two elements, but (Host,port), bound host, port number to socket
Socket.listen (): A parameter that allows the client to connect to the server's queued line, if it exceeds the pending upper limit will be rejected, start listening to the bound port number
Socket.accept (): No parameter, its return value is a tuple, the first is a new socket object, the second is the address, passively accepts the TCP client link, the arrival of the blocking wait connection
Socket.connect (): Active initialization of TCP server connections
SOCKET.CONNECT_EX (): Extended version of Connect (), error returning the fault code, not throwing an exception
Python socket programming