Introduction to the Socket function
socket.
socket
(
family=af_inet,
type=sock_stream,
proto=0,
fileno=none)
Create a new socket using the given address family, socket type and protocol number. The address family should beAF_INET
(the default),AF_INET6
,AF_UNIX
,AF_CAN
OrAF_RDS
. The socket type should beSOCK_STREAM
(the default),SOCK_DGRAM
,SOCK_RAW
Or perhaps one of the otherSOCK_
Constants. The protocol number is usually zero and could be omitted or in the case where the address family isAF_CAN
The protocol should be one ofCAN_RAW
OrCAN_BCM
. IfFilenowas specified, the other arguments was ignored, causing the socket with the specified file descriptor to return. Unlikesocket.fromfd()
,FilenoWould return the same socket and not a duplicate. This could help close a detached socket usingsocket.close()
.
socket.
getaddrinfo
(host, Port, family=0, type=0, proto=0, flags=0 ) must be
Gets the peer host address to connect to
Sk.bind (address) must be
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) must be
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) must be
Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.
sk.accept () must be
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) must be
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 () must be
Close socket
sk.recv (Bufsize[,flag]) must be
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]) must be
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]) must be
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) must be
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 () must be
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
socket.
sendfile
(file, offset=0, count=none)
Send files, but most of the time there are no eggs.
Basic Socket Instance
Server-Side instances
#! /usr/bin/env python# _*_ Coding utf-8 _*_#author:aaronimport socketserver = Socket.socket () # Generate socket handle # server = so Cket.socket (AF. INET, Sock_stream) server.bind ((' localhost ', 6960) # bind monitored port server.listen (5) # Listen for the bound port print (' waitting ... ') conn, addr = Server.accept () # waits for Client connection print (conn, addr) while True: Data = CONN.RECV (1024x768) # receive Client C15/>print (' recv: ', Data.decode ()) conn.send (data) # sends a message to the client Conn.close ()
Client instance
#! /usr/bin/env python# _*_ Coding utf-8 _*_#author:aaronimport socketclient = Socket.socket () # Generate socket handle client.connect ((' localhost ', 9999) # link Server side while True: msg = input (' >> '). Strip () if msg = = 0:continue client.send (Msg.encode (' Utf-8 ')) # Send data to server ( ' client.recv: ') print Data.decode ()) # Receive server-side data client.close ()
Problems that exist
- Server-side exception after client exits
After the client exits, the server side is still executing the recv function, and the server side will always receive null characters and cannot be stopped.
Simply put, it is possible to send two data in a row, which may not be what the programmer wants to see in the form of a packet.
Simple version of SSH implementation
This simple version of the SSH implementation, it solves the above two problems. In the sticky packet processing, as long as the two consecutive sent data between the receiving ACK signal received, so that two consecutive data generated by the sticky packet will appear.
Server-side
#! /usr/bin/env python# _*_ Coding utf-8 _*_#author:aaronimport socketserver = Socket.socket () server.bind (' localhost ', 9999)) Server.listen (5) while true:conn, addr = Server.accept () print (' New conn: ', addr) while true:data = CONN.RECV (1024) # Client disconnects, server-side exception handling scheme if not data:print (' Customer disconnected ') Break print (' Execute instruction : ', data ' cmd_res = Os.popen (Data.decode ()). Read () # receive string, execution result is also string print (' Cmd_res num: ', Len (cmd_res)) If Len (cmd_res) = = 0:cmd_res = ' No that commond! haha ' # conn.send (str (cmd_res.encode (' Utf-8 ')). Encode (' Utf-8 ')) #可能存在粘包 # send_res = Conn.send (Cmd_res.encode (' Utf-8 ')) #的可能 #print (send_r ES) conn.send (str (cmd_res.encode (' Utf-8 '))). Encode (' Utf-8 ')) #time. Sleep (0.5) Client_ack = CONN.R ECV (1024x768) # Wait client to confirm print (' Ack from client: ', Client_ack.decode ()) # sticky packet processing send_res = conn. Send (Cmd_res.encode (' Utf-8')) Server.close ()
Client
#! /usr/bin/env python# _*_ Coding utf-8 _*_#author:aaronimport socketclient = Socket.socket () client.connect (' localhost ' , 9999)) while True: cmd = input (' >> '). Strip () if len (cmd) = = 0:continue client.send (Cmd.encode (' Utf-8 ') cmd_size = Client.recv (1024x768) client.send (' ready to accept '. Encode (' Utf-8 ')) #做粘包处理 Received_data = B ' received_size = 0 while received_size! = Int (Cmd_size.decode ()): Received_data = CLIENT.RECV (1024) C10/>received_size + = Len (received_data) print (Received_data.decode ()) #print (' received_size: ', Received_size) Else: print (' cmd recv done ... ') #print (' received_size: ', received_size) #print (Cmd_res.decode ()) Client.close ()
Python's Socket Network programming