Socket more detailed introduction in this article do not explain, interested students can go online to find relevant information or directly https://docs.python.org/3/library/socket.html view
Simple understanding, the socket is the more bottom of the FTP, UDP and other protocols to carry out a package, not how they do three handshake four times, only exposed to us a send data and recv receive data. Because the most essential role of communication between the two sides is to send and receive data.
One, declare a socket object
SK = Socket.socket (socket.af_inet,socket. sock_stream,0)
Parameter one: Address cluster
Socket.af_inet IPv4 (default)
Socket.af_inet6 IPV6
Socket.af_unix can only be used for single UNIX system interprocess communication
Parameter two: type
Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP
Socket. Sock_raw the original socket, the ordinary socket can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, in addition, the use of the original socket, can be IP_ The HDRINCL socket option constructs an IP header by the user.
Socket. SOCK_RDM is a reliable form of UDP that guarantees the delivery of datagrams but does not guarantee the order. Sock_ram is used to provide low-level access to the original protocol, which is used when certain special operations are required, such as sending ICMP packets. Sock_ram is typically used only by advanced users or by programs that are run by administrators.
Socket. Sock_seqpacket Reliable Continuous Packet service
Parameter three: protocol
0 (default) protocol related to a particular address family, if 0, the system will automatically select an appropriate protocol based on the address format and socket category.
Second, Socket object method
#Server-SideS.bind ()#The binding address (Host,port) to the socket, under Af_inet, represents the address in the form of a tuple (host,port). S.listen ()#start TCP snooping. 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. S.accept ()#passively accepts TCP client connections, (blocking) waits for a connection to arrive#ClientS.connect ()#actively initializing the TCP server connection. 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. S.CONNECT_EX ()#Extended version of the Connect () function, which returns an error code instead of throwing an exception when an error occurs#PublicS.RECV ()#receives TCP data, the data is returned as a string, and bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. S.send ()#sends the TCP data to the connected socket by sending the data in the string. The return value is the number of bytes to send, which may be less than the byte size of the string. S.sendall ()#complete sending of TCP data, 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. S.recvfrom ()#The UDP data is received, 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. S.sendto ()#sends UDP data, sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifies the remote address. The return value is the number of bytes sent. S.close ()#Close SocketS.getpeername ()#returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port). S.getsockname ()#returns the socket's own address. Typically a tuple (ipaddr,port)S.setsockopt (Level,optname,value)#sets the value of the given socket option. S.getsockopt (Level,optname[.buflen])#returns the value of the socket option. S.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 Connect ())S.gettimeout ()#returns the value of the current timeout, in seconds, or none if the timeout period is not set. S.fileno ()#returns the file descriptor for the socket. S.setblocking (flag)#If flag is 0, the socket is set to nonblocking mode, otherwise the socket is set to blocking 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. S.makefile ()#create a file associated with the socket
View CodeThird, simple example
Service side:
1 ImportSocket2 3Ip_port = ('127.0.0.1', 9999)4 5SK =Socket.socket ()6 Sk.bind (Ip_port)7Sk.listen (5)8 whileTrue:9 Print('Server Waiting ...')TenCONN,ADDR =sk.accept () One Print("New Conn:", addr) A - whileTrue: - Try: thedata = CONN.RECV (1024) - Print(data) - Print(Data.decode ()) - Conn.send (Data.upper ()) + exceptConnectionreseterror as E: - Print("duankaile ...", E) + Break
Client:
1 ImportSocket2 3Ip_port = ('127.0.0.1', 9999)4Client =Socket.socket ()5 Client.connect (Ip_port)6 7 whileTrue:8data = input ("Client Input:"). Strip ()9 ifLen (data) = =0:Ten Continue OneClient.sendall (Data.encode ("Utf-8")) Aserver_reply = CLIENT.RECV (1024) - Print("Client Received:", Server_reply.decode ())
The server is set while true for a dead loop, which can be looped to the client's request.
PS: Another point to note is that in Python2, when the client disconnects, it will send some empty data to the server loop, so if the Python2 user can directly judge if not data:break to jump out of the client's service.
However, in the Python3 processing as a direct error, so you need to catch this connectionreseterror error, and then break off.
Python Learning Notes (socket programming)