One, socket
Sockets are objects that provide the current portable standard for network application providers on a specific network protocol (such as TCP/IP,ICMP/IP,UDP/IP, etc.) suite pair. They allow the program to accept and make connections, such as sending and receiving data. In order to establish a communication channel, it is extremely important for each endpoint of a network communication to have a socket object.
Sockets are part of the BSD Unix system core, and they are also adopted by many other Unix-like operating systems including Linux. Many non-BSD Unix systems, such as the Ms-dos,windows,os/2,mac OS and most host environments, provide support for sockets in the form of libraries.
The three most popular types of sockets are: Stream,datagram and raw. Stream and datagram sockets can interface directly with the TCP protocol, while the raw sockets interface to the IP protocol. However, sockets are not limited to TCP/IP.
Two, Socket module
The socket module is a very simple object-based interface that provides access to the low-level BSD socket style network. Use this module to implement client and server sockets. To build a simple server with TCP and streaming sockets in Python, you need to use the socket module. Using the functions and class definitions contained in the module, you can generate programs that communicate over the network. In general, it takes six steps to establish a server connection.
The 1th step is to create the socket object. Call the socket constructor.
Socket=socket.socket (Familly,type)
The value of family can be Af_unix (UNIX domain for interprocess communication on the same machine) or af_inet (TCP and UDP for IPV4 Protocol), as for the type parameter, SOCK_STREAM (stream socket), or Sock_ Dgram (data message socket), SOCK_RAW (RAW socket).
The 2nd step is to bind (assign) the socket to the specified address, socket.bind (address)
Address must be a two-element tuple, ((Host,port)), host name or IP address + port number. If the port number is being used or reserved, or if the hostname or IP address is wrong, a Socke.error exception is thrown.
3rd step, after binding, you must have the socket ready to accept the connection request.
Socket.listen (Backlog)
The backlog specifies the maximum number of connections, at least 1, after the connection request is received, the requests must be queued, and if the queue is full, the request is rejected.
4th, the server socket waits for the client to request a connection through the socket's Accept method:
Connection,address=socket.accept ()
When the Accept method is called, the socket enters the ' waiting ' (or blocked) state. When a client requests a connection, the method establishes the connection and returns the server. The Accept method returns a tuple that contains two elements, such as (connection,address). The first element (connection) is the new socket object through which the server communicates with the customer, and the second element (address) is the customer's Internet address.
The 5th step is the processing phase where the server and the customer communicate via the Send and Recv methods (transfer data). The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to accept information from the customer. When calling recv, you must specify an integer to control the maximum amount of data that is accepted by this call. The Recv method enters the ' Blocket ' state when the data is accepted, and finally returns a string that represents the received data. If the amount sent exceeds the allowable recv, the data is truncated. The excess data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer.
6th step, the transfer ends, the server calls the socket's Close method to close the connection.
Establishing a simple client connection requires 4 steps.
1th step, create a socket to connect to the server Socket=socket.socket (Family,type)
2nd step, connect to Server Socket.connect ((host,port)) using the socket's Connect method
3rd, the client and server communicate via the Send and recv methods.
At the end of the 4th step, the customer closes the connection by calling the Close method of the socket.
Steps for Python to write server:
The first step is to create the socket object. Call the socket constructor. Such as:
Socket = Socket.socket (family, type)
The family parameter represents the address family, which can be either af_inet or Af_unix. The Af_inet family includes Internet addresses, and the Af_unix family is used for interprocess communication on the same machine.
The type parameter represents a socket type, which can be sock_stream (stream sockets) and Sock_dgram (datagram sockets).
The second step is to bind the socket to the specified address. This is done through the bind method of the Socket object:
Socket.bind (Address)
The socket created by AF_INET, the address must be a two-element tuple in the format (host,port). Host, Port represents the port number. The Bind method throws an Socket.error exception if the port number is in use, the hostname is incorrect, or the port has been persisted.
The third step is to use the Listen method of the socket socket to receive the connection request.
Socket.listen (Backlog)
The backlog specifies the maximum number of clients that are allowed to connect to the server. It has a value of at least 1. When a connection request is received, the requests are queued and the request is rejected if the queue is full.
The fourth step is that the server socket waits for the client to request a connection through the socket's accept method.
Connection, address = socket.accept ()
When the Accept method is called, the socket is in the "Waiting" state. When a client requests a connection, the method establishes the connection and returns the server. The Accept method returns a tuple containing two elements (connection,address). The first element, connection, is the new socket object that the server must communicate with the customer, and the second element address is the customer's Internet location.
The fifth step is the processing phase where the server and the client communicate via the Send and Recv methods (transfer data). The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to receive information from the customer. When calling recv, the server must specify an integer that corresponds to the maximum amount of data that can be received through this method call. The Recv method enters the "blocked" state when it receives the data, and finally returns a string that represents the received data. If the amount of data sent exceeds the allowable recv, the data will be truncated. The excess data will be buffered on the receiving side. When Recv is called later, the extra data is removed from the buffer (and any other data that the customer may have sent since the last call to Recv).
At the end of the transfer, the server calls the socket's Close method to close the connection.
Steps for Python to write the client:
Create a socket to connect to the server: socket = socket.socket (family, type)
Connect to the server using the socket's Connect method. For the Af_inet family, the connection format is as follows:
Socket.connect ((Host,port))
Host represents the server host name or ip,port the port number that is bound on behalf of the server process. If the connection succeeds, the client can communicate with the server through the socket, and if the connection fails, a Socket.error exception is thrown.
Processing phase, the client and the server communicate through the Send method and the Recv method.
At the end of the transfer, the client closes the connection by calling the Close method of the socket.
Here's a simple example:
server.py
Copy the Code code as follows:
if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.bind ((' localhost ', 8001))
Sock.listen (5)
While True:
Connection,address = Sock.accept ()
Try
Connection.settimeout (5)
BUF = CONNECTION.RECV (1024)
if buf = = ' 1 ':
Connection.send (' Welcome to server! ')
Else
Connection.send (' Please go out! ')
Except Socket.timeout:
print ' Time Out '
Connection.close ()
client.py
Copy CodeThe code is as follows:
if __name__ = = ' __main__ ':
Import socket
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.connect ((' localhost ', 8001))
Import time
Time.sleep (2)
Sock.send (' 1 ')
Print SOCK.RECV (1024)
Sock.close ()
Running server.py at the terminal and then running clien.py will print "Welcome to server!" at the terminal. If you change client.py's Sock.send (' 1 ') to a different value in the terminal will print "Please go out!", Change Time.sleep (2) to a value greater than 5, the server will time out.
Example:
Service side:
Copy the Code code as follows:
#socket Server Side
#获取socket构造及常量
From socket Import *
# ' on behalf of server ' localhost '
MyHost = ' '
#在一个非保留端口号上进行监听
MyPort = 50007
#设置一个TCP Socket Object
Sockobj = socket (af_inet, SOCK_STREAM)
#绑定它至端口号
Sockobj.bind ((MyHost, MyPort))
#监听, allow 5 links
Sockobj.listen (5)
#直到进程结束时才结束循环
While True:
#等待下一个客户端连结
Connection, address = sockobj.accept ()
#连结是一个新的socket
print ' Server connected by ', address
While True:
#读取客户端套接字的下一行
data = CONNECTION.RECV (1024)
#如果没有数量的话, then jump out of the loop
If not data:break
#发送一个回复至客户端
Connection.send (' echo=> ' + data)
#当socket关闭时eof
Connection.close ()
Client:
Copy the Code code as follows:
Import Sys
From socket Import *
ServerHost = ' localhost '
ServerPort = 50007
#发送至服务端的默认文本
message = [' Hello network World ']
#如果参数大于1的话, the service end of the connection is the first parameter
If Len (SYS.ARGV) > 1:
ServerHost = sys.argv[1]
#如果参数大于2的话, the text of a link is the second argument
If Len (SYS.ARGV) > 2:
Message = Sys.argv[2:]
#建立一个tcp/IP Socket Object
Sockobj = socket (af_inet, SOCK_STREAM)
#连结至服务器及端口
Sockobj.connect ((ServerHost, ServerPort))
For line in message:
#经过套按字发送line至服务端
Sockobj.send (line)
#从服务端接收到的数据, capped at 1k
data = SOCKOBJ.RECV (1024)
#确认他是引用的, it's ' X '.
print ' Client received: ', repr (data)
#关闭套接字
Sockobj.close ()