Python Socket Network Programming steps detailed (socket socket use) _python

Source: Internet
Author: User
Tags reserved sleep string format truncated in python

One, socket
Sockets are objects that provide the current portability standard for a network application provider on a specific network protocol (such as TCP/IP,ICMP/IP,UDP/IP, etc.). They allow programs to accept and connect, 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 core of BSD Unix systems, 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 socket support in the form of libraries.
The three most popular types of sockets are: Stream,datagram and raw. The stream and datagram sockets can interface directly with the TCP protocol, while the raw socket interfaces to the IP protocol. However, sockets are not limited to TCP/IP.

Second, Socket module

A socket module is a very simple object-based interface that provides access to low-level BSD socket style networks. Use this module to implement client and server sockets. To create 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 this 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 a socket object. Call the socket constructor.

Socket=socket.socket (Familly,type)
The family value can be Af_unix (UNIX domain for interprocess communication on the same machine), or af_inet (for TCP and UDP for the IPV4 protocol), for type parameters, Sock_stream (stream sockets), or Sock_ Dgram (data packet socket), SOCK_RAW (RAW socket).

The 2nd step is to bind (assign) the socket to the specified address, socket.bind

The address must be a two-element tuple, ((Host,port)), a hostname, or IP addresses + port number. If the port number is being used or reserved, or if the host name or IP address is incorrect, a Socke.error exception is thrown.

Step 3rd, after binding, you must have a socket ready to accept the connection request.

Socket.listen (Backlog)
Backlog Specifies the maximum number of connections, at least 1, after a connection request, these requests must be queued, and if the queue is full, the request is rejected.

Step 4th, the server socket waits for a client to request a connection through the accept method of the socket:
Connection,address=socket.accept ()
When the Accept method is invoked, the socket enters the ' waiting ' (or blocked) state. When a client requests a connection, the method establishes the connection and returns to the server. The Accept method returns a tuple containing two elements, in the form of (connection,address). The first element (connection) is a new socket object that the server communicates with the customer, and the second element (address) is the client's Internet addresses.

The 5th step is the processing phase, in which the server and the client communicate (transmit data) through the Send and recv methods. The server invokes send and sends the message to the customer in a string format. 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 it accepts data, and finally returns a string that represents the received data. If the amount sent exceeds the allowable recv, the data is truncated. The extra 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 Close method to turn off the connection.

It takes 4 steps to establish a simple customer connection.

Step 1th, create a socket to connect to the server Socket=socket.socket (Family,type)
2nd, connect the server Socket.connect ((host,port)) using the Connect method of the socket
3rd step, the client and the server communicate through the Send and recv methods.
After the 4th step, the customer closes the connection by calling the Close method of the socket.


Python to write server steps:

The first step is to create a socket object. Call the socket constructor. Such as:
Socket = Socket.socket (family, type)
The family parameter represents the address family and can be 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 and 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)
Socket created by af_inet, address must be a two-element tuple, in the form of (Host,port). Host stands for Hosts and port represents the port number. If the port number is in use, the host name is incorrect, or the port is reserved, the Bind method throws a Socket.error exception.

The third step is to receive the connection request using the Listen method of the socket socket.
Socket.listen (Backlog)
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, these requests need to be queued and the request is rejected if the queue is full.

The fourth step is that the server socket waits for a client to request a connection through the accept method of the socket.
Connection, address = socket.accept ()
When the Accept method is invoked, the socket will be in the "Waiting" state. When a client requests a connection, the method establishes the connection and returns to the server. The Accept method returns a tuple (connection,address) that contains two elements. The first element connection is a new socket object that the server must communicate with the customer, and the second element address is the client's Internet addresses.

The fifth step is the processing phase, in which the server and the client communicate (transmit data) through the Send and recv methods. The server invokes send and sends the message to the customer in a string format. 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 is truncated. The extra data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer (and any other data that the customer may send since the last call to Recv).
At the end of the transfer, the server calls the Close method of the socket to turn off the connection.


Python's steps to write a client:

Create a socket to connect to the server: socket = socket.socket (family, type)
Connect the server using the Connect method of the socket. 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 the server process is bound to. If the connection succeeds, the customer 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 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 Code code 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 in the terminal, then running clien.py, will print "Welcome to server!" in the terminal. If you change the Sock.send (' 1 ') of the client.py to print "Please go out!" for other values at the terminal, and change the value of Time.sleep (2) greater than 5, the server will timeout.

Example:
Service side:

Copy Code code as follows:

#socket Server Side
#获取socket构造及常量
From socket Import *
# ' represents the server for 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 ' and 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 Code code as follows:

Import Sys
From socket Import *
ServerHost = ' localhost '
ServerPort = 50007
#发送至服务端的默认文本
message = [' Hello network World ']
#如果参数大于1的话, the connected server is the first parameter
If Len (SYS.ARGV) > 1:
ServerHost = sys.argv[1]
#如果参数大于2的话, the linked text 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)
#从服务端接收到的数据 with a maximum of 1k
data = SOCKOBJ.RECV (1024)
#确认他是引用的, is ' x '
print ' Client received: ', repr (data)
#关闭套接字
Sockobj.close ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.