Python path socket, socket server

Source: Internet
Author: User

First, socket

The English literal of the socket is "hole" or "socket". As the BSD UNIX process communication mechanism, take the latter one meaning. usually also
Called sockets, which describe IP addresses and ports, is a handle to a communication chain that can be used to communicate between different virtual machines or different computers. Hosts on the internet typically run multiple service software, while providing several services. Each service opens a socket and binds to a port, and the different ports correspond to different services. The socket is like a porous socket, as its English intended. A host is like a room full of various sockets, each outlet has a number, some sockets provide 220 vac, some provide 110 volts AC, some provide cable TV programs. Customer software plug into different numbered sockets, you can get different services

2. Connection principle
Depending on how the connection is started and the destination to which the local socket is connected, the connection between sockets can be divided into three steps: Server listening, client request, connection acknowledgement.

(1) Server monitoring: Is the server end socket does not locate the specific client socket, but in the status of waiting for the connection, real-time monitoring network status.

(2) Client request: Refers to the client's socket to make a connection request, to connect to the target is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.

(3) Connection confirmation: When the server-side socket is heard or received a client socket connection request, it responds to the client socket request, set up a new thread, the server-side socket description to the client, once the client confirms the description, the connection is established. While the server-side socket continues to be in the listening state, it continues to receive connection requests from other client sockets.

Case

1. The simplest Web server

#! /USR/BIN/ENV python#coding:utf-8# Importing Socket module Import socket  #开启ip和端口ip_port = (' 127.0.0.1 ', 8080) #生成句柄web = Socket.socket () #绑定端口web. bind (Ip_port) #最多连接数web. Listen (5) #等待信息print (' Nginx waiting ... ') #开启死循环while True:    #阻塞    conn,addr = web.accept ()    #获取客户端请求数据    data = CONN.RECV (1024x768)    #打印接受数据 Note: When the browser accesses, the data is received by the browser information, etc.    print (data)    #向对方发送数据    conn.send (bytes (' 

2. Simple Chat Tool

(1) Service side

#! /usr/bin/env python    #coding: Utf-8 import socket# turn on IP and port ip_port = (' 127.0.0.1 ', 9999) #生成一个句柄sk = Socket.socket () # Bind IP Port sk.bind (ip_port) #最多连接数sk. Listen (5) #开启死循环while True:    print (' Server waiting ... ')    #等待链接, block until channel link Conn opens a new object specifically to the current linked client addr is the IP address    conn,addr = sk.accept ()    #获取客户端请求数据    client_data = conn.recv (1024x768)    #打印对方的数据    Print (str (client_data, ' UTF8 '))    #向对方发送数据    conn.sendall (' Don't answer, don't answer, don't answer ', ' UTF8 ')    #关闭链接    conn.close ()

(2) Client side

#! /usr/bin/env python#coding:utf-8import socket# linked server IP and port ip_port = (' 127.0.0.1 ', 9999) #生成一个句柄sk = Socket.socket () # Request Connection server-side sk.connect (Ip_port) #发送数据sk. Sendall (Bytes (' Yaoyao ', ' utf8 ') #接受数据server_reply = Sk.recv (1024x768) #打印接受的数据print ( STR (server_reply, ' UTF8 ')) #关闭连接sk. Close ()

3. More Versatile

More Versatile 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 so Cket. 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 automatically chooses an appropriate protocol sk.bind (address) s.bind (addr ESS) binds a socket to an address. The format of address addresses depends on the address family. Under Af_inet, address is represented as a tuple (host,port). Sk.listen starts listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected. The backlog equals 5, indicating that the kernel has received a connection request, but the server has not yet called the accept to handle the maximum number of connections to 5, this value cannot be infinitely large, because to maintain the connection queue sk.setblocking (bool) in the kernel is blocked (by default true), If set to False, then the accept and recv when no data, then the error. Sk.accept () Accepts the 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. Receive TCP GuestConnected (blocked) wait for the connection to arrive Sk.connect (address) to connect to the socket at address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection. SK.CONNECT_EX (address), except that there will be a return value, the connection succeeds when return 0, the connection fails when the return encoding, for example: 10061sk.close () Close socket SK.RECV (Bufsize[,flag]) accept the socket data. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored. Sk.recvfrom (Bufsize[.flag]) is 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. Sk.send (String[,flag]) 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. That is, the specified content may not be sent all. Sk.sendall (String[,flag]) sends the data in a string to the connected socket, but attempts to send all the data before returning. Successful return none, Failure throws an exception. Internally, the send is called recursively, sending all the content. Sk.sendto (string[,flag],address) sends 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. This function is mainly used for UDP protocol. Sk.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, because they may be used for connected operations (such as client connections waiting up to 5s) Sk.getpeername () to return the remote address of the connection socket. The return value is typically a tuple (ipaddr,port). Sk.getsockname () returns the socket's own address. Typically a tuple (ipaddr,port) Sk.fileno () a file descriptor for a socket
Second, Socket server

The Socketserver internally uses IO multiplexing and "multithreading" and "multi-process" to enable the socket service side to process multiple client requests concurrently. That is, when each client requests a connection to the server, the socket server is creating a "thread" or "process" dedicated to all requests from the current client.

Note: When the module is imported, the 3.x version is Socketserver 2.x version is Socketserver

1.ThreadingTCPServer

The Soket server implemented by Threadingtcpserver creates a "thread" for each client that is used to interact with the client.

    1. Threadingtcpserver Base uses threadingtcpserver:

Create a class that inherits from Socketserver.baserequesthandler
A method called handle must be defined in a class
Start Threadingtcpserver

Service side

Import Socketserverclass MyServer (socketserver.baserequesthandler):d EF handle (self):    conn = Self.request    Conn.sendall (' I am multithreaded ')    flag = True while    flag:        data = CONN.RECV (1024x768)        if data = = ' exit ':            flag = False        elif data = = ' 0 ':            conn.sendall (' you entered 0 ')        else:            conn.sendall (' please reenter. ') if __name__ = = ' __main__ ': Server = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 8009), MyServer) server.serve_forever ()

Client

#!/usr/bin/env python #-*-coding:utf-8-*-Import Socket ip_port = (' 127.0.0.1 ', 8009) SK = Socket.socket () sk.connect (IP _port) while True:     data = SK.RECV (1024x768)     print ' Receive: ', data     INP = input (' Please input: ')     Sk.sendall (INP)     if InP = = ' exit ': Break     Sk.close ()

The internal invocation process is:
    • Start the service-side program
    • Execute tcpserver. init method, creating a server-side socket object and binding IP and ports
    • Execute baseserver. The init method assigns a custom class-myrequesthandle that inherits from Socketserver.baserequesthandler to self. Requesthandlerclass
    • Executes the Baseserver.server_forever method, while the loop is always listening for client requests to arrive ...
      When a client connection arrives at the server
    • Executes the Threadingmixin.process_request method, creating a "thread" to handle the request
    • Execute the Threadingmixin.process_request_thread method
    • Executes the Baseserver.finish_request method and executes self. Requesthandlerclass () is the construction method that executes the custom Myrequesthandler (automatically calls the constructor of the base class Baserequesthandler, which in turn calls the Handle method of Myrequesthandler)
Forkingtcpserver

The use and execution processes of forkingtcpserver and threadingtcpserver are basically consistent, except that "threads" and "processes" are created internally for the requestor.

Python path socket, socket server

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.