Conquer Python-socket

Source: Internet
Author: User

Socket

Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.

Sk.bind (Address)

S.bind binds the socket to the address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port).

Sk.listen (Backlog)

Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected.

The backlog equals 5, indicating that the kernel has received a connection request, but the server has not yet called the accept to process the maximum number of connections is 5
This value cannot be infinitely large because the connection queue is maintained in the kernel

Sk.setblocking (BOOL)

Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.

Sk.accept ()

Accepts the 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.

Incoming TCP Client connection (blocked) waiting for connection

Sk.connect (Address)

The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.

SK.CONNECT_EX (Address)

Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061

Sk.close ()

Close socket

SK.RECV (Bufsize[,flag])

Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.

Sk.recvfrom (Bufsize[.flag])

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.send (String[,flag])

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. That is, the specified content may not be sent all.

Sk.sendall (String[,flag])

Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.

Internally, the send is called recursively, sending all the content.

Sk.sendto (string[,flag],address)

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. This function is mainly used for UDP protocol.

Sk.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 client connections waiting up to 5s)

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.fileno ()

File descriptor for sockets

ImportSocket Server= Socket.socket ()#To generate a socket handle#Server = Socket.socket (AF. INET, Sock_stream)Server.bind (('localhost', 6960))#ports for binding monitoringServer.listen (5)#listening on the bound portPrint('waitting ...') conn, addr= Server.accept ()#Waiting for client connectionsPrint(conn, addr) whileTrue:data= CONN.RECV (1024)#receiving client Data    Print('recv:', Data.decode ()) conn.send (data)#sending data to the clientconn.close ()
Server-Side
ImportSocket Client= Socket.socket ()#To generate a socket handleClient.connect (('localhost', 9999))#Linked server-side  whiletrue:msg= Input ('>>'). Strip ()ifmsg = = 0:Continueclient.send (Msg.encode ('Utf-8'))#send data to server sidedata = CLIENT.RECV (1024)    Print('recv:', Data.decode ())#receiving server-side dataclient.close ()
Client

Problems that exist

1. When the client disconnects, the server side will automatically disconnect the error.

Workaround: A. Add exception handling mechanism.

B. The server side determines whether the accepted string is empty (after the client disconnects, it continues to send the null character).

C. The server uses Socketserver.

2. Possible sticky packet problem (send function sends data, there is a mechanism to send the data to reach the buffer hour or after an acceptance delay, and then unified send, not send once).

Workaround: A. Each sending a file, the receiving party receives a true received value after receiving, avoids the continuous sending.

B. Before sending a file, send the file size to the receiver so that the recipient receives only the appropriate size of the data.

Implement a simple SSH

ImportSocket,os#instantiate a socketSer=Socket.socket ()#bind IP to PortSer.bind (('localhost', 9999))#MonitorSer.listen () whileTrue:#blocking, waiting for links    Print("Start waiting! ") conn,addr=ser.accept () whileTrue:#Accept Commands        Try: Data=CONN.RECV (1024)            #Execute command return character            Print("start executing the command! ") Cmd_res=Os.popen (Data.decode ()). Read ()ifLen (cmd_res) = =0:cmd_res="Command Error"            #Send character lengthConn.send (str (LEN (Cmd_res.encode ("Utf-8")). Encode ("Utf-8"))            #accept responses to prevent sticky packetsCONN.RECV (1024)            #Send command resultConn.send (Cmd_res.encode ("Utf-8"))            Print("Send complete! ")        exceptException as E:Print(e) Break
Server-Side
ImportSocket#declaring a Socket objectCli=Socket.socket ()#linksCli.connect (("localhost", 9999)) whileTrue:#input CommandCmd=input (">>:")    #Transfer CommandCli.send (Cmd.encode ("Utf-8")) Data_size=int (CLI.RECV (1024). Decode ()) Cli.send (b" $") Recv_data=b""recv_size=0#Loop through the data until it's closed.     whileData_size>recv_size:#Prevent sticky bags        ifdata_size-recv_size<1024: Size=data_size-recv_sizeElse: Size=1024#Accept DataData=cli.recv (size) recv_size+=len (data) Recv_data+=DataElse:        Print(Recv_data.decode ())
Client

Conquer Python-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.