1, Socket parameter introduction
A network socket is a endpoint of a connection across a computer network. Today, most communication between computers are based on the Internet Protocol; Therefore most network sockets is the Internet sockets. More precisely, a socket was a handle (abstract reference) that a local program can pass to the networking application prog Ramming interface (API) to use the connection, for example "Send this data in this socket".
2, Socket parameter introduction
socket.
socket
(
family=af_inet,
type=sock_stream,
proto=0,
fileno=none) will
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.
socketpair
([family[, type[, Proto]])
Build a pair of connected socket objects using the given address family, socket type, and protocol number. Address family, socket type, and protocol number is as for the socket()
function above. The default family AF_UNIX
is if defined on the platform; otherwise, the default is AF_INET
.
socket.
create_connection
address [,  timeout [, source_address ]]
Connect to a TCP service listening on the internet address (a 2-tuple port)
), and return the socket object. This is a higher-level function Than Socket.connect ()
: if host is a non-numeric hostname, it'll try to resolve it for BOTH&N Bsp af_inet
and af_inet6
, and then try to connect to all possible Addresses in turn until a connection succeeds. This makes it easy-to-write clients that is compatible to both IPV4 and IPv6.
Passing the optional timeout parameter would set the timeout on the socket instance before attempting to connect. If No timeout is supplied, the global default timeout of setting returned is getdefaulttimeout()
used.
If supplied, source_address must is a 2-tuple for the socket to bind to as its (host, port)
source address before Connec Ting. If host or port is ' or 0 respectively the OS default behavior would be used.
socket.
getaddrinfo
(host, Port, family=0, type=0, proto=0, flags=0) # Gets the peer host address to connect to must be
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.
3. Basic socket Instance server side (on Linux)
ImportSocket,subprocessserver=socket.socket () Server.bind ('0.0.0.0', 8000)) Server.listen (5)Print("---Waiting for client---") whiletrue:conn,addr=server.accept ()#Conn is a connection instance that the client is connected to and generated on the server. Print(CONN,ADDR) whileTrue:Try: Data=CONN.RECV (1024) Print("recv:", Data.decode ()) Res_obj=subprocess. Popen (data,shell=true,stdout=subprocess. Pipe,stderr=subprocess. PIPE) Res=Res_obj.stdout.read () conn.send (str (RES)). Encode ()) Conn.send (res)exceptException as E:Print(e) Break
Client Side
Importsocketclient=socket.socket () Client.connect ("localhost", 8000)) whiletrue:msg=input (">>:"). Strip ()ifLen (msg) ==0:ContinueClient.send (Msg.encode ()) Data=CLIENT.RECV (1024) Total_size=Int (Data.decode ()) Resive_size=0 Res=b"' whileresive_size<total_size:d=CLIENT.RECV (1024) Res+=D resive_size+=Len (d)Print(Res.decode ())
Socket Network Programming One