Python Network programming socket

Source: Internet
Author: User

First, socket

Python provides two basic socket modules.

The first one is the Socket, which provides the standard BSD Sockets API.

The second is Socketserver, which provides a server-centric class that simplifies the development of Web servers.

The two programs on the network realize the exchange of data through a two-way communication connection, one end of this connection is called a socket. Often also referred to as "sockets" is used to describe IP addresses and ports, is a communication chain of the sentence

Let's look at a simple example:

ImportSocketsk=socket.socket () Sk.bind ('127.0.0.1', 8000,)) Sk.listen (5) whiletrue:conn,address=sk.accept () conn.sendall (bytes ('Welcome to visit! ', encoding='Utf-8'))     whileTrue:ret= str (CONN.RECV (1024x768), encoding='Utf-8')        Print(ret)ifRET = ='Q':             BreakConn.sendall (bytes (ret+' Nice', encoding='Utf-8') ) Sk.close ()
Server-Side
ImportSocketobj=socket.socket () Obj.connect ('127.0.0.1', 8000,)) whileTrue:ret_str= str (OBJ.RECV (1024x768)), encoding='Utf-8')    Print(RET_STR) INP=input ('Please enter what you want to send:')    ifINP = ='Q': Obj.sendall (bytes (inp,encoding='Utf-8'))         Break    Else: Obj.sendall (bytes (INP, encoding='Utf-8') ) Obj.close ()
Client

The above example has a very obvious problem such as the client and the server is already connected to the communication, if there is a client to connect to only wait, through the socketserver can be implemented by multiple clients simultaneous connection please see the example:

ImportSocketserverclassMysocket (Socketserver. Baserequesthandler):#You must inherit this class    defHandle (self):#The handle method is executed first when calledconn = Self.request#self.request refers to the connection of the clientConn.sendall (Bytes ('Welcome to visit! ', encoding='Utf-8'))         whileTrue:ret= str (CONN.RECV (1024x768), encoding='Utf-8')            Print(ret)ifRET = ='Q':                 BreakConn.sendall (bytes (ret+' Nice', encoding='Utf-8'))if __name__=='__main__': obj= Socketserver. Threadingtcpserver (('127.0.0.1', 8000), Mysocket) Obj.serve_forever ()
Server

The client code has not changed. Let's talk about the socket type parameter.

Socket format:

Socket (Family,type[,protocal]) creates a socket with the given address family, socket type, protocol number (default = 0).

Socket function:

###### #服务端socket函数 ###### #sk. Bind (address): Binds a socket to an address and, under Af_inet, represents it in the form of a tuple (host,port). Sk.listen (Backlog): Starts listening for TCP incoming connections. 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. Sk.accept (): Accepts a TCP connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client. ###### #客户端socket函数 ###### #sk. Connect: The socket connected to address. 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. SK.CONNECT_EX (adddress): function is the same as connect (address), but successfully returns 0, failure returns the value of errno. ###### #公共socket函数 ###### #sk. recv (Bufsize[,flag]): Accepts data for TCP sockets. The data is returned in bytes, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. Sk.send (String[,flag]): Sends TCP data. Sends data from a string to a connected socket. The return value is the number of bytes to send, which may be less than the byte size of the string. Sk.sendall (String[,flag]): 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. Sk.recvfrom (Bufsize[.flag]): Accepts data for UDP sockets. 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. Sk.sendto (string[,flag],address): Sends UDP data. Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. Sk.close (): Closes the socket. Sk.getpeername (): Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port). Sk.getSockname (); Returns the socket's own address. Typically a tuple (ipaddr,port) sk.setsockopt (level,optname,value): Sets the value of the given socket option. Sk.getsockopt (Level,optname[.buflen]): Returns the value of the socket option. Sk.settimeout (Timeout): Sets the timeout period for a 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 ()) Sk.gettimeout (): Returns the value of the current timeout period, in seconds, or none if no timeout has been set. Sk.fileno (): Returns the file descriptor of the socket. Sk.setblocking (flag): If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to block 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. Sk.makefile (): Create a file associated with the socket

Implement command command format for cmd| command via Socketserver and subprocess.

ImportSocketserverImportsubprocessclassMyserver (socketserver. Baserequesthandler):defhandle (self): whileTrue:conn=self.request conn.sendall (bytes ("Welcome to login","UTF8"))             whiletrue:client_bytes=CONN.RECV (1024)                if  notClient_bytes: BreakClient_str=str (Client_bytes,"UTF8")                Print(CLIENT_STR) Func,command=client_str.split ("|", 1) Result_str=subprocess.getoutput (command) result_bytes= Bytes (result_str,encoding='UTF8') Info_str="info|%d"%Len (result_bytes) conn.sendall (bytes (INFO_STR,"UTF8") ) Conn.sendall (result_bytes) conn.close ()if __name__=="__main__": Server=socketserver. Threadingtcpserver (("127.0.0.1", 9998), Myserver) Server.serve_forever ()
Service Side
ImportSocketip_port=("127.0.0.1", 9998) SK=Socket.socket () sk.connect (Ip_port)Print("client-initiated ...")Print(Str (SK.RECV (1024),"UTF8")) whileTRUE:INP=input ("Please input:"). Strip ()ifInp.startswith ("cmd"): Sk.sendall (bytes (INP,"UTF8")) Basic_info_bytes=SK.RECV (1024)        Print(Str (basic_info_bytes,"UTF8")) Result_length=int (str (basic_info_bytes,"UTF8"). Split ("|") [1])        Print(result_length) has_received=0 content_bytes=bytes () whilehas_received<result_length:fetch_bytes=SK.RECV (1024) has_received+=Len (fetch_bytes) content_bytes+=fetch_bytes Cmd_result=str (Content_bytes,"UTF8")        Print(Cmd_result) sk.close ()
Client

  

  

  

Python Network programming socket

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.