The so-called server is a series of hardware or software, for one or more clients (service users) to provide the required ' service '. The only reason it exists is to wait for the client's request and respond to them (providing the service), and then wait for more requests. On the other hand, the client contacts the server for a specific request, sends the necessary data, waits for the server to respond, and finally completes the request or gives the fault information. The server runs indefinitely and continues to process requests, while the client makes a one-time request, receives the service, and ends the transaction between them.
Currently the most common client/server architecture, which depicts multiple clients retrieving information from a single server over the Internet.
650) this.width=650; "Src=" https://s5.51cto.com/wyfs02/M01/94/C8/wKiom1kNtVHjBMaxAAEyuR4jlQs152.png-wh_500x0-wm_ 3-wmp_4-s_1253242509.png "title=" Cs.png "alt=" Wkiom1kntvhjbmaxaaeyur4jlqs152.png-wh_50 "/>
Socket (socket) is a computer network data structure, it embodies the concept of ' communication endpoint '. A network application must create a socket before any type of communication begins. They can be likened to a telephone jack, without which it will not be able to communicate.
Sockets originate from UNIX, and one of Unix/linux's basic philosophies is "Everything is File", which is used to open, read, write, and close the file. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is to do it (read/write Io, open, close). Sockets typically have two types: file-based and network-oriented.
The first type is file-based Af_unix, which is mainly used for two interprocess communication on the same computer, and the second is network-oriented af_inet, which is mainly used for communication between computers on the Internet.
Typically, network sockets are divided into connection-oriented sockets and non-connected sockets. Connection-oriented communication provides serialized, reliable, and non-repeatable data delivery without logging boundaries. The primary protocol for implementing this type of connection is Transmission Control Protocol (TCP). In order to create a TCP socket, you must use SOCK_STREAM as the socket type.
650) this.width=650; "Src=" https://s1.51cto.com/wyfs02/M00/94/C7/wKioL1kNuirxcQHrAAIiU6YdWeE573.png-wh_500x0-wm_ 3-wmp_4-s_944185683.png "title=" Qq20170506195317.png "alt=" Wkiol1knuirxcqhraaiiu6ydwee573.png-wh_50 "/>
In contrast to the Transmission Control protocol, a datagram-type socket is a non-connected socket. This means that there is no need to establish a connection before the communication begins. At this point, the data transfer process does not guarantee its sequencing, reliability, or repeatability. However, the datagram preserves the record boundaries, which means that the message is sent as a whole rather than broken into multiple fragments. The primary protocol that implements this type of connection is User datagram (UDP). In order to create a UDP socket, you must use SOCK_DGRAM as the socket type.
650) this.width=650; "Src=" https://s4.51cto.com/wyfs02/M00/94/C7/wKioL1kNu4KROpmoAAGWVo9QX2E780.png-wh_500x0-wm_ 3-wmp_4-s_324579738.png "title=" Qq20170506195251.png "alt=" Wkiol1knu4kropmoaagwvo9qx2e780.png-wh_50 "/>
S=socket (Family,type, proto=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: Connection type
Socket. Sock_stream streaming socket, for TCP (default)
Socket. SOCK_DGRAM datagram socket, for UDP
Socket. Sock_raw original sockets, ordinary sockets can not handle ICMP, IGMP and other network messages, and Sock_raw May, second, Sock_raw can also handle special IPV4 messages, using 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 will automatically select an appropriate protocol based on the address format and socket category. |
Server Socket method
| S.bind (Address) |
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). |
| S.listen (Backlog) |
Start listening for incoming connections. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected. |
| S.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. Incoming TCP Client connection (blocked) waiting for connection |
Client Socket method
| S.connect (Address) |
The socket that is connected to the address. The format of address is a tuple (hostname,port) and returns a socket.error error if there is an error in the connection.
|
| S.CONNECT_EX (Address) |
Ibid., except that there will be a return value, return 0 when the connection succeeds, and return the encoding when the connection fails, instead of throwing an exception. |
Common socket methods
| S.RECV (Bufsize[,flag]) |
Receives the data for the socket. 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. |
S.recv_into ()
|
Receives a TCP message to the specified buffer. |
| Sk.recvfrom (Bufsize[.flag]) |
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.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. |
| S.sendall (String[,flag]) |
Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception. Internally via recursive invocation
Send, sending all the contents out. |
| S.sendto (string[,flag],address) |
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. This function is mainly used for UDP protocol. |
| 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 (ipaddr,port) |
Blocking-oriented socket method
| S.setblocking (BOOL) |
Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error. |
| S.settimeout (Timeout) |
Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. Value is
None means there is no super-period. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as client connections waiting up to 5s) |
| S.gettimeout () |
Gets the timeout period for blocking socket operations |
File-oriented socket methods
| S.fileno () |
File descriptor for sockets |
S.makefile ()
|
Create a socket associated file object |
Server-side:
# !/usr/bin/env python# -*- coding:utf-8 -*-"This script creates a TCP server that receives messages from the client and prints them on the terminal, returning the current timestamp "' from socket import *from time import ctimehost = ' PORT = 12345BUFSIZ = 1024ADDR = (Host,port) tcpsersock = socket (af_inet,sock_ STREAM) Tcpsersock.bind (ADDR) Tcpsersock.listen (5) while true: print (' waiting For connection ') tcpclisock,addr=tcpsersock.accept () Print (' ... connected from: ', addr) while True:    DATA=TCPCLISOCK.RECV (bufsiz) print (str (data, ' Utf-8 ')) if not data: break tcpclisock.send (Bytes (CTime (), ' Utf-8 ')) tcpclisock.close () Tcpsersock.close ()
Client:
#!/usr/bin/env python#-*-coding:utf-8-*-from socket Import *host = ' 127.0.0.1 ' PORT = 12345BUFSIZ = 1024ADDR = (host,po RT) Tcpclisock = socket (af_inet,sock_stream) Tcpclisock.connect (ADDR) while true:data = input (' > ') if not data: Break Tcpclisock.send (bytes (data, ' utf-8 ')) data = TCPCLISOCK.RECV (bufsiz) if not data:break Prin T (str (data, ' Utf-8 ')) Tcpclisock.close ()
Operation Result:
Server-side:
Waiting for connection......connected from: (' 127.0.0.1 ', 62735) 1231234345345567
Client:
> 123Sat 6 21:31:06 2017> 1234Sat May 6 21:32:44 2017> 3453Sat could 6 21:32:46 2017> 45Sat May 6 21:32: 2017> 567Sat May 6 21:32:48 2017>
Server-side:
Socket *time Ctimehost = PORT = Bufsiz = ADDR = (host,port) Udpsersock = socket (af_inet,sock_dgram) Udpsersock.bind (ADDR): () data,addr = Udpsersock.recvfrom (Bufsiz) ((data,)) Udpsersock.sendto ((CTime (),), addr) (, addr) udpsersock.cl OSE ()
Client:
Socket *host = PORT = Bufsiz = ADDR = (host,port) Udpclisock = socket (Af_inet,sock_dgram): Data= () DATA:UDPCL Isock.sendto (data,), ADDR) Data,addr=udpclisock.recvfrom (bufsiz) Data: ((data,)) Udpclisock.close ()
Output Result:
Server-side:
Waiting for message ... 123...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ... 12334...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ... 123...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ... 14...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ... 234...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ... 5...received form and return to: (' 127.0.0.1 ', 58765) waiting for message ...
Client:
>123sun 7 11:59:46 2017>12334sun May 7 12:02:32 2017>1231sun could 7 12:02:33 2017>42sun May 7 12:02:34 2017>34sun 7 12:02:34 2017>5sun May 7 12:02:35 2017>
Socketserver is an advanced module in the standard library, which is designed to simplify many boilerplate code, which is required to create network clients and servers. There are a variety of classes in this module that help programmers hide specific implementation details, while handling transactions in the form of a face object helps organize the data and logically puts the functionality in the right place. In Python3 Socketserver renamed to Socketserver.
The inheritance relationship between each class:
| Baseserver | | v| TCPServer |------->| Unixstreamserver | | v| Udpserver |------->| Unixdatagramserver |
| Class |
Describe |
|
Baseserver |
Hooks that contain core server functionality and Mix-in classes are used only for derivation, so that instances of this class are not created: You can create an instance of the class with TCPServer or Udpserver |
| Tcpserver/udpserver |
Network synchronization TCP/UDP Server based on |
|
Unixstreamserver/
Unixdatagramserver |
File-based base synchronization TCP/UDP server |
The above four service classes are synchronous requests, that is, one request cannot process the next request until it is processed. When you want to support an asynchronous model, you can use multiple inheritance to let the server class inherit the Forkingmixin or ThreadingMixIn class.
| Class |
Describe |
|
forkingmixin/
ThreadingMixIn |
Core dispatch or Threading function: only function mix-in class domain A server class mates to implement some asynchrony; it cannot be instantiated directly. |
|
forkingtcpserver/
Forkingudpserver |
Combination of Forkingmixin and tcpserver/udpserver, using multiple processes to implement asynchronous |
| threadingtcpserver/
Threadingudpserver |
A combination of threadingmixin and tcpserver/udpserver that uses multithreading to implement asynchronous |
In the Socketserver module, server processing requests are implemented primarily through the Baserequesthandler class, where multiple processing functions can be used.
Setup ()
The initialization action to perform the request is called before the handle () method, and nothing is done by default.
Handle ()
This function must complete all requests to the server, and some instance properties are available to it.
Request through the Self.request function,
The client address is passed the Self.client_address function,
The server instance passes the Self.server function,
Self.request for streaming services Self.request is a socket object, and for a data message Self.request is a series of strings and sockets.
Finish ()
Call this method after the handle () function, perform a request cleanup operation, do nothing by default, and this function will not be called if Setup () has an exception.
server-side instances :
Socketserver (TCPServer TCP, Streamrequesthandler SRH) Time Ctimehost = PORT = ADDR = (host,port) myrequesthandler (SRH): Setup (): () handle (): Conn=.request (,. client_address) ((Conn.recv (),)) Conn.send ((c Time (),)) Finish (): () () Tcpserv = TCP (Addr,myrequesthandler) () Tcpserv.serve_forever ()
Client instance:
Socket *host = PORT = Bufsiz = ADDR = (host,port): Tcpclisock = socket (af_inet,sock_stream) tcpclisock.connect (ADDR) Data= () data:tcpCliSock.send (data,)) DATA=TCPCLISOCK.RECV (bufsiz) Data: ((data,)) Tcpcliso Ck.close ()
Operation Result:
Server-side:
Waiting for connection ... Before processing the request!!! ... connected from: (' 127.0.0.1 ', 62042) 1223 after processing the request!!! ----------------------before processing the request!!! ... connected from: (' 127.0.0.1 ', 62051) 123 after processing the request!!! ----------------------before processing the request!!! ... connected from: (' 127.0.0.1 ', 62052) 5435 after processing the request!!! ----------------------before processing the request!!! ... connected from: (' 127.0.0.1 ', 62053) 574 after processing the request!!! ----------------------before processing the request!!! ... connected from: (' 127.0.0.1 ', 62054) 68 after processing the request!!! ----------------------
Client:
>1223sun 7 13:01:45 2017>123sun May 7 13:01:46 2017>5435sun could 7 13:01:47 2017>574sun May 7 13:01:48 2017>68sun May 7 13:01:49 2017>
This article is from the "Wind and Drift" blog, please be sure to keep this source http://yinsuifeng.blog.51cto.com/10173491/1922818
Python Network programming