Python Advanced Trilogy Network programming

Source: Internet
Author: User

When using Python for network programming, the communication port that connects to the specified server process is actually in the process of the Python program itself, so network traffic can also be seen as a communication between two processes.

One of the concepts mentioned in network programming is that Socket,socket is an abstraction of network programming, usually when we open a network connection with a socket, and opening a socket requires knowing the IP address and port number of the target computer, and then specifying the co-type.

Python provides two basic socket modules:

    1. The standard BSD Sockets API is available
    2. Socketserver provides a server-centric class that simplifies the development of Web servers.
Socket type.

The socket format is: socket (family,type[,protocal]), using the given metro, socket type, protocol number (default 0) to create the socket.

Socket type and description.

Socket Type Description
Socket.af_unix Can only be used for a single UNIX system process to ask for communication
Socket.af_inet network communication between servers
Socket.af_inet6 IPv6
Socket. Sock_stream Streaming socket, with TCP
Socket. Sock_dgram Teach a reported 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, using the original socket, the IP header can be constructed by the user through the IP_HDRINCL socket option
Socket. Sock_seopacket Reliable, continuous packet service
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
Socket function

The socket function and description.

Socket Function Description
- Service-side functions
S.bind (Address) Bind a socket to an address, afinet, in the form of a tuple chost.port)
S.listen (Backlog) Start listening for TCP-descendants double-click. 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 () Accept TCP connections on return (Conn,addes), 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 (hostoame,port) and returns a socket.error error if there is an error in the connection
S.CONNECT_EX (adddress) The function is the same as CONNCCT (address), but successfully returns 0, and the value of the failed return to the same Ermno
- 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 often be ignored
S.send (Stringc,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 exception
S.recvfrom (Bufsize[.flag]) Accepts data for UDP sockets. Similar to Recv0, but the return value is Data,addres). Where data is the string that contains the received information, and address is the socket that sends 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 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 (ipadd.port)
S.setsockopt (Level,optname,value) Sets the value of a 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, Timcout is a floating-point number in seconds. A value of None indicates no over-time. General timeout periods should be set when a socket is just created, as they may be used for connection operations (such as Connect ())
S.setblocking (flag) If the 0, the socket is set to non-blocking mode, otherwise the socket is set to block mode (the default value). In non-blocking mode, if the call recv () does not find any data, or the Send () call cannot send the data immediately, the SOCKET.ERROR exception is caused
TCP Programming

Network programming generally includes the meat part: Server and client, TCP is a connection-oriented communication mode, actively initiates the connection called the client, the passive response of the connection called the server.

To create a service side:

The first thing to say about servers is that it takes 5 steps to create and run a service:

    1. Create the socket, bind the socket to the local IP and port.
    2. Start listening for connections
    3. Enter the loop and continue to receive customer connection requests
    4. Receive incoming data and send it to the other data.
    5. When the transfer is complete, close the socket.
# coding:utf-8import socketimport threadingimport timedef dealClient(sock, addr):    # 接收传来的数据,并发送给对方数据。    print(‘Accpet new conn from %s:%s‘ % addr)    sock.send(b‘hello, i am server‘)    while True:        data = sock.recv(1024)        time.sleep(1)        if not data or data.decode(‘utf-8‘) == ‘exit‘:            break        print(‘%s!‘ % data.decode(‘utf-8‘))        sock.send((‘Loop_msg:%s!‘ % data.decode(‘utf-8‘)).encode(‘utf-8‘))    # 关闭socket    sock.close()    print(‘conn from %s:%s close.‘ % addr)if __name__ == "__main__":    # 第一步:创建一个基于IPV4和TCP协议的Socket    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    # socket绑定IP(127.0.0.1为本机IP)与端口。    s.bind((‘127.0.0.1‘, 9999))    # 监听连接。    s.listen(5)    print(‘wating for conn...‘)    while True:        # 接收一个新连接,        sock, addr = s.accept()        # 创建新线程来处理TCP连接。        t = threading.Thread(target=dealClient, args=(sock, addr))        t.start()
To create a client:
    1. Create a socket to connect to the remote address.
    2. Send data and receive data after the connection.
    3. When the transfer is complete, close the socket
import socket# 初始化Sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 连接目标的IP和端口。s.connect((‘127.0.0.1‘, 9999))# 接收数据,print(‘-->>‘, s.recv(1024).decode(‘utf-8‘))# 发送数据。s.send(b‘Hello,i am a client‘)print(‘-->>‘ + s.recv(1024).decode(‘utf-8‘))s.send(b‘exit‘)# 关闭sockets.close()先运行,服务端,再运行客户端,得到:-->> hello, i am server-->>Loop_msg:Hello,i am a client!
UDP programming,

TCP communication requires a process of establishing a reliable connection, and both sides of the communication send data in the form of a stream. Relative TCP,UDP is a non-connected protocol, using the UDP protocol, do not need to establish a connection, only need to know the other side's IP address and port number, you can send the packet directly, but do not care whether to reach the destination, although the use of UDP transmission data is unreliable, but because it does not establish a connection process, The speed is much faster than TCP, and for data that does not require reliable arrival, the UDP protocol can be used.

Using the UDP protocol, like TCP, there are server and room end points, UDP programming compared to TCP programming is relatively simple, the server to create and run only 3 steps:

    1. Creates a socket that binds the specified IP and port.
    2. Send data and receive data directly,
    3. Close socket
To create a service side:
# coding:utf-8import socket# 创建Socket,绑定指定的IP和端口。# SOCK_DGRAM 指定了这个Socket的类型是UDP,绑定端品和TCP示例一样。s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)s.bind((‘127.0.0.1‘, 9999))print(‘bind udp on 9999...‘)while True:    # 直接发送数据和接收数据。    data, addr = s.recvfrom(1024)    print(‘received from %s:%s.‘ % addr)    s.sendto(b‘hello,%s!‘ % data, addr)
Create Client

Create a socket that can be exchanged directly with the server for data exchange.

# coding:utf-8import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)for data in [b‘hello‘, b‘world‘,b‘python‘,b‘android‘,b‘java‘]:    # 发送数据    s.sendto(data, (‘127.0.0.1‘, 9999))    # 接收数据,    print(s.recv(1024).decode(‘utf-8‘))s.close()得到:hello,hello!hello,world!hello,python!hello,android!hello,java!

The above is the UDP server and room-side data interaction process, UDP use and TCP type, but do not need to establish a connection, in addition, the servers bound UDP port and TCP port do not conflict, that is, UDP 9999 port and TCP 9999 ports can be bound respectively.

Python Advanced Trilogy Network programming

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.