Make a little progress every day!
First, the Python learning socket syntax and related
1-1 What is a Socket
On the same computer, the process can communicate this way, if it is a different computer? A network socket (socket) is used to communicate with different computers on the network. Sockets are an abstraction of communication between different computers. He works on an abstraction between the application layer and the transport layer in the TCP/IP protocol. The socket guarantees communication between different computers, that is, network communication. For Web sites, the communication model is communication between client servers. Each of the two terminals establishes a socket object and then transmits the data through the socket object. For example, a host address of 80 port via TCP 1.2.3.4 sends "Hello, world!! ", connect to the remote host, send the string, and then turn off communication:
Socket socket = Getsocket (type = "TCP") #设定好协议类型
Connect (socket, address = "1.2.3.4", port = "#连接远程机器")
Send (Socket, "Hello, world!") #发送消息
Close (socket) #关闭连接
1-2 Socket Families (address cluster)
socket.AF_UNIX unix本机进程间通信
socket.AF_INET IPV4
socket.AF_INET6 IPV6
1-3 Socket Types
socket.SOCK_STREAM #for tcp
socket.SOCK_DGRAM #for udp
socket.SOCK_RAW #原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
socket.SOCK_RDM #是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
socket.SOCK_SEQPACKET #废弃了
How to 1-4 sockets
Socket method
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 be af_inet (the default), Af_inet6, Af_unix, Af_can or af_rds. The socket type should besock_stream (the default), Sock_dgram, Sock_raw or perhaps one of the other Sock_ constants. The protocol number is usually zero and could be omitted or in the case where the address family is af_can the protocol Shou LD be one of Can_raw or can_bcm. If Fileno is specified, the other arguments be ignored, causing the socket with the specified file descriptor to return. Unlike SOCKET.FROMFD (), Fileno would return the same socket and not a duplicate. This could help close a detached socket using socket.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 is Af_unix 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 (host, Port)), and return the socket object. This was a higher-level function than Socket.connect (): If host is a non-numeric hostname, it would try to resolve it for Bo Th 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 by Getdefaulttimeout () is used.
If supplied, source_address must is a 2-tuple (host, port) for the socket to bind to as its source address before Connecti Ng. 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) #获取要连接的对端主机地址
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
Socket.sendfile (file, offset=0, Count=none)
Send the file, but most of the time it is not used.
Second, Python learning socketserver implementation of multiple concurrency
Server-side:
Import socketserver
Class Mytcphandler (Socketserver. Baserequesthandler):
""
the request handler class for our server.
It is instantiated once per connection to the server, and must
override the handle () method to implement Communic ation to the
client.
"" "
Def handle (self):
# self.request are the TCP socket connected to the client
Self.data = SELF.REQUEST.R ECV (1024x768). Strip ()
print ("{} wrote:". Format (self.client_address[0))
Print (self.data)
# just send back the Same data, but upper-cased
Self.request.sendall (Self.data.upper ())
If __name__ = = "__main__":
HOST, PORT = "localhost", 9999
# Create The server, binding to localhost on port 9999
Server = Socketserver. TCPServer (HOST, PORT), Mytcphandler)
# Activate the server; this'll keep running until you
# interrupt the Program with Ctrl-c
Server.serve_forever ()
Client:
Import socket
Import Sys
HOST, PORT = "localhost", 9999
data = "". Join (sys.argv[1:])
# Create A socket (sock_stream means a TCP socket)
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Try
# Connect to server and send data
Sock.connect ((HOST, PORT))
Sock.sendall (Bytes (data + "\ n", "Utf-8"))
# Receive data from the server and shut down
Received = str (SOCK.RECV (1024x768), "Utf-8")
Finally
Sock.close ()
Print ("Sent: {}". Format (data))
Print ("Received: {}". Format (Received))
The above example does not implement multiple concurrency, make a change on the server side can be
Put
Server = Socketserver. TCPServer (HOST, PORT), Mytcphandler)
Change into
Server = Socketserver. Threadingtcpserver (HOST, PORT), Mytcphandler)
Beginner Python's Day8