(Note: This article is part of the content from the Internet, due to the author's limited, shortcomings, but also hope to comment.) )
National Day eight days off, has been over 3 days, plus tomorrow is the mid-Autumn festival, or decided to write this evening before the writing finished. National Day in Ningbo hometown, eat good drink good sleep, is no good reading, small regret.
The dog forced Brother Yong said---National day to take me together in the hometown of the tavern talk about life, the results ran to Guangdong to go to the girls, the stingy high school group is fast over the mid-Autumn festival, neither the moon cakes nor send red envelopes. Oh, good. But fortunately, the mosquitoes at home are special sticky people ... Also, the hometown of the month, is also an exceptionally round.
let's start with the text. (The previous article spoke of UDP)
First, the concept of sockets
A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.
The socket is the Post Office mail bucket, and your letter must be placed in an envelope to be mailed. The post office doesn't care about your letter, he only cares where he comes from. The letter is equivalent to TCP/IP or UDP messages, the content of the message is the content of the letter. To put it simply, the socket is a package for TCP/IP or UDP interfaces.
Second, communications
Communication is based on the Ip+port can be targeted to the specific machine specific services, the operating system has 0-65535 ports, each port can be independent of external services, if a company than do a computer, the company's switchboard number is equivalent to the IP address, each employee's extension number is equivalent to the port, If you want to find someone in the company, you must call the switchboard first and then the extension.
using UDP to send is relatively simple and does not require encryption, whereas using TCP/IP requires a connection (three handshake) and a disconnection (four waves).
Three-time handshake (connection established):
1. First handshake: When a connection is established, the client sends a SYN packet to the server, waiting for the server to confirm.
2. Second handshake: The server receives the SYN packet, responding to a syn-ack packet.
3. Third handshake: The client receives the server's Syn-ack packet, sends the acknowledgment packet ack to the server, and the packet is sent complete, three times the handshake.
Four waves (disconnect):
1. First handshake: The client sends a FIN packet to the server, indicating that the client has no data to send to the server, waiting for the server to confirm.
2. Second handshake: The server receives the fin packet, sends an ACK packet to confirm the client's fin packet, and does not send the FIN package if the server data has not been passed.
3. Third handshake: When the server does not have the data to send to the client, the server sends a FIN packet to the client and waits for the client to finalize the confirmation.
4. Fourth handshake: The client receives the FIN packet, sends an ACK packet to confirm the server's Fin packet, the packet is sent complete, four times the handshake is completed, and the two sides are disconnected.
Third, socket type (common)
Socket. Sock_stream streaming socket, for TCP
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 the IPV4 message;
In addition, using the original socket, the IP header can be constructed by the user through the IP_HDRINCL socket option.
Create a TCP Socket:s=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Create a UDP Socket:s=socket.socket (socket.af_inet,socket. SOCK_DGRAM)
Four, socket commonly used functions:
Note the point:
1.TCP when sending data, a TCP connection is established, so you do not need to specify an address. UDP is for non-connected, each time it is sent to specify who to send.
2. The server and client cannot send the list, tuple, dictionary directly. Requires a string of repr (data).
( while Python3 can only send byte type, string to B ' or encode to utf-8)
|
Socket function |
Describe |
|
Service-Side socket function |
|
S.bind (Address) |
Binds a socket to an address, and under Af_inet, the address is represented as a tuple (host,port). (Refers to the server address) |
|
S.listen (Backlog) |
Starts listening for TCP incoming connections. 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 () |
Accepts a TCP 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. |
|
Client socket function |
|
S.connect (Address) |
The socket that is connected to the address. 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 (adddress) |
function is the same as connect (address), but successfully returns 0, the value of errno is returned. |
|
Common socket function |
|
S.RECV (Bufsize[,flag]) |
Accepts data for TCP sockets. The data is returned as a string, bufsize specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored. |
|
S.send (String[,flag]) |
Send TCP data. 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. |
|
S.sendall (String[,flag]) |
Send TCP data in full. 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 (Bufsize[.flag]) |
Accepts data for UDP sockets. 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 (string[,flag],address) |
Send UDP data. 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. |
|
S.close () |
Close the socket. |
|
S.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 |
Five, socket programming ideas (take TCP/IP as an example)
TCP Service side:
1 creating sockets, binding sockets to local IP and ports
# Socket.socket (Socket.af_inet,socket. SOCK_STREAM), S.bind ()
2 Start listening for connection #s. Listen ()
3 Enter the loop and continuously accept the client's connection request #s. Accept ()
4 then receive the incoming data, and send the data #s. recv (), S.sendall ()
5 When the transfer is complete, close the socket #s. Close ()
TCP Client:
1 creating sockets, connecting remote addresses
# Socket.socket (Socket.af_inet,socket. SOCK_STREAM), S.connect ()
2 Send data and receive data after connection # S.sendall (), S.RECV ()
3 When the transfer is complete, close the socket #s. Close ()
Six, small examples
Given the limitations of ability and time, give a small example.
Service side:
Import= ('127.0.0.1', 9877= socket.socket () s.bind (Ip_port) S.listen (5= s.accept () while True: = conn.recv (1024x768) Print(client_data) Conn.sendall (b'123456' ) ) Conn.close ()
Client:
Import= ('127.0.0.1', 9877= socket.socket () s.connect (ip_ Port) while 1: = input ("fa:") S.sendall ( Data.encode ()) = S.recv (1024x768) print(server_reply) s.close ()
Operation Result:
OK, the socket will be over first.
Everyone went out to play on national Day, on my hometown of Ningbo 8th tour.
In fact, I like to stay at home, do not love to go out to play, mainly because---poor.
Python Socket Network Programming (II)