Python3 Socket Network Programming

Source: Internet
Author: User

A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.

Socket originated from UNIX, in Unix everything is file philosophy, socket is an "open-read/write-off" mode implementation, the server and the client maintain a "file", after establishing a connection open, you can write to their own files for the other side to read or read the contents of the other side, Closes the file at the end of the communication. The English meaning of the socket is "slot" or "socket", just like our home landline, if there is no network cable of that socket, the phone is unable to communicate. The socket is an interface for implementing the TCP,UDP protocol and facilitates the use of TCP,UDP.

#Process Description:# #1 servers Create sockets based on address type (IPV4,IPV6), socket type, protocol# #2 server binds IP address and port number to socket# #3 server Socket Listener port number request, ready to receive the client's connection, this time the server socket is not opened# #4 Client Create socket# #5 client opens socket, attempts to connect to server socket based on server IP address and port number# #6 The server socket receives a client socket request, passively opens, and begins receiving client requests until the client returns the connection information. At this point the socket enters the blocking state, # The so-called blocking-accept () method waits until the client returns the connection information before returning, starting to receive the next client connection request# #7 Client Connection successful, sending connection status information to the server# #8 Server Accept method returned, connection successful# #9 The client writes information to the socket (or the server writes information to the socket)# #10 Server Read information (client read information)# #11 Client Shutdown# #12 server-side shutdown

Server-side s.bind ()#The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port). S.listen ()#start TCP snooping. The backlog specifies the maximum number of connections that the operating system can suspend before rejecting the connection. This value is at least 1, and most applications are set to 5. s.accept ()#passively accepts TCP client connections, (blocking) waits for a connection to arriveclient S.connect ()#actively initializing the TCP server connection. The format of the general address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection. s.connect_ex ()#Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occursfunction S.recv for public use ()#receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. s.send ()#sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string. S.sendall ()#complete sending of TCP data, complete sending of TCP data. Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception. s.close ()#Close SocketS.recvform ()#The UDP data is received, similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data. s.sendto ()#sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent. S.getpeername ()#returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port). S.getsockname ()#returns the socket's own address. Typically a tuple (ipaddr,port)s.setsockopt (Level,optname,value)#sets the value of the given socket option. s.getsockopt (Level,optname[.buflen])#returns the value of the socket option. s.settimeout (Timeout)#sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as Connect ())s.gettimeout ()#returns the value of the current timeout, in seconds, or none if the timeout period is not set. S.fileno ()#returns the file descriptor for the socket. s.setblocking (flag)#If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking mode (the default value). In nonblocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the Socket.error exception is raised. S.makefile ()#create a file associated with the socket

Simple instance Service side

We use the socket function of the socket module to create a socket object. The socket object can set up a socket service by calling other functions.

We can now specify port (port) of the service by invoking the bind (hostname) function.

Next, we call the Accept method of the socket object. The method waits for the client to connect and returns a Connection object that indicates that the client is connected.

The complete code is as follows:

ImportSocket#Importing the Socket moduleSK= Socket.socket ()#creating a Socket objectSk.bind (("127.0.0.1", 8888))#bind port, "127.0.0.1" for native address, 8888 for the port address of the set linkSk.listen (5)#set up a listener with up to 5 clients to queueconn, addr = Sk.accept ()#blocking state, passively waiting for a client connectionPrint(conn)#Conn can understand the client's socket object#<socket.socket fd=4, Family=addressfamily.af_inet, Type=socketkind.sock_stream, proto=0, laddr= (' 127.0.0.1 ', 9005), raddr= (' 127.0.0.1 ', 36694) >Print(addr)#addr The port address of the client#(' 127.0.0.1 ', 40966)Accept_data = CONN.RECV (1024)#CONN.RECV () receives the contents of the client, receives the bytes type data,Accept_data2 = str (accept_data, encoding="UTF8")#str (data,encoding= "UTF8") is decoded with "UTF8"Print("". Join ("Receive content:", Accept_data2,"Client Port:", str (addr[1] )) Send_data= Input ("enter what to send:") Conn.sendall (bytes (send_data, encoding="UTF8"))#Send content must be bytes type data, bytes (data, encoding= "UTF8") encoded in "UTF8" formatConn.close ()
Client

Next we write a simple client instance that connects to the service created above. The port number is 8888.

The socket.connect (hosname, Port) method opens a TCP connection to a service provider that hosts a port of "127.0.0.1". After the connection we can start from the service end of the data, remember that the operation will need to close the connection after completion.

The complete code is as follows:

ImportSocketsk=socket.socket () Sk.connect ("127.0.0.1", 8888))#proactively initialize connections to the server sideSend_data = input ("enter what to send:") Sk.sendall (bytes (send_data, encoding="UTF8")) Accept_data= SK.RECV (1024)Print(Str (Accept_data, encoding="UTF8") ) Sk.close ()

Above just realize the service side of the receive and send, below we upgrade can continue to communicate:

Service side
ImportSocketsk=socket.socket () Sk.bind ("127.0.0.1", 9008)) Sk.listen (5) whileTrue:conn, addr=sk.accept () whileTrue:accept_data= STR (CONN.RECV (1024), Encoding="UTF8")        Print("". Join (["Receive content:", Accept_data,"Client Port:", str (addr[1])]))        ifAccept_data = ="Byebye":#if "Byebye" is received, it jumps out of the loop end and communicates with the first client, and begins to communicate with the next client.             BreakSend_data= Input ("enter the send in P capacity:") Conn.sendall (bytes (send_data, encoding="UTF8") ) Conn.close ()#end communication When jumping out of a loop
Client
ImportSocketsk=socket.socket () Sk.connect ("127.0.0.1", 9008))#proactively initialize connections to the server side whileTrue:send_data= Input ("enter what to send:") Sk.sendall (bytes (send_data, encoding="UTF8"))    ifSend_data = ="Byebye":         BreakAccept_data= str (SK.RECV (1024x768), encoding="UTF8")    Print("". Join ("Receive content:", Accept_data))) Sk.close ()

In the above simple example, the client must be queued to communicate with the server, only the current customer after the end of communication with the server to communicate with the service, then there is no way to allow multiple clients to communicate with the server at the same time? Then we need to use the Socketserver module:

Simple concurrent instance Service side
ImportSocketserver#Import socketserver ModuleclassMyServer (Socketserver. Baserequesthandler):#create a class that inherits from the Baserequesthandler class under the Socketserver module    defHandle (self):#To implement a concurrency effect, you must override the handler method in the parent class to implement the logical code on the server side (no further write connection preparation, including bind (), listen (), accept () method)         while1: Conn=self.request Addr=self.client_address#The above two lines of code, equal to CONN,ADDR = Socket.accept (), but in the Socketserver module has been packaged for us, but also for us packaging including bind (), listen (), the Accept () method             while1: Accept_data= str (CONN.RECV (1024x768), encoding="UTF8")                Print(Accept_data)ifAccept_data = ="Byebye":                     BreakSend_data= Bytes (Input (">>>>>"), encoding="UTF8") Conn.sendall (send_data) conn.close ()if __name__=='__main__': Sever= Socketserver. Threadingtcpserver (("127.0.0.1", 8888), MyServer)#incoming port address and our newly created Baserequesthandler class instantiation object that inherits from the Socketserver moduleSever.serve_forever ()#activates the server by invoking the Serve_forever () method of the object
Client
ImportSocketsk=socket.socket () Sk.connect ("127.0.0.1", 8888))#proactively initialize connections to the server side whileTrue:send_data= Input ("enter what to send:") Sk.sendall (bytes (send_data, encoding="UTF8"))    ifSend_data = ="Byebye":         BreakAccept_data= str (SK.RECV (1024x768), encoding="UTF8")    Print("". Join ("Receive content:", Accept_data))) Sk.close ()

Python3 Socket Network Programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.