Theme
- Client/server architecture
- Socket: End of communication
- Socket address
- Connection-oriented and non-connected sockets
- Network programming in Python
- Socket module
- Socket Object Methods
- TCP/IP client and server
- UDP/IP Client and server
- Socketserver Module
- Twisted Framework Introduction
- Related modules
1. Client Server ArchitectureCustomers <---->INTERNET<-------> Servers. The client connects to a pre-known server, presents its own request, sends the necessary data, and waits for the data returned by the server.
2. Socket: End of communicationA socket is a computer network data structure with the concept of "communication endpoint". Networked applications need to create sockets before they begin any communication, just like a telephone jack, without which they will not be able to communicate at all. Python only supports the Af_unix,af_netlink,af_inet family, because we only care about network programming so we use only af_inet.
3. Socket addressIf the socket is likened to a telephony interface----------the lowest-level structure of communication, the host and Port are like a pair of combinations of area codes and phone numbers. It's not enough to have a phone, you need to know who you want to call and where to go. An Internet address consists of a host and a port that must be used for network communication, and the other end must be heard. The legal port number range is 0~65535, where the port number less than 1024 is reserved for the system.
4. Connection-oriented and non-connected sockets(1) connection-oriented regardless of which address family is used, there are only two types of sockets, connection-oriented and no-connection. Connection-oriented is the need to establish a connection before communication, just like calling a friend. The primary protocol for implementing this connection is Transmission Control Protocol (TCP), which is created by specifying a socket type of sock_stream when creating a TCP socket. The TCP socket uses the name Sock_stream to reflect its most current socket characteristics, because these sockets use Internet Protocol (IP) to find the host network, so the formation of the entire system, the general will have two protocol (TCP and IP) name of the combination to describe, namely TCP/IP. (2) No connection is required to communicate without a connection. However, the order, reliability, and repeatability of data arrival cannot be guaranteed. The data is sent throughout, and is not split into small chunks like a connection-oriented protocol. The primary protocol for implementing this connection is the User Datagram Protocol (UDP). To create a UDP socket, you specify that the socket type is SOCK_DGRAM when you create it. "Datagram" is a "datagram".
network Programming in the 5.PythonWe will use the socket module in Python and the socket () function in the module to create the socket. To use the Socket.socket () function to create a socket, the syntax is as follows: Socket.socket (socket_family,socket_type,protocol=0) As mentioned earlier, socket_family is not AF_VNI X is af_inet, Socket_type can be sock_stream or sock_dgram,protocol generally not fill, default is 0.
6.SOCKET ModuleFor example, to create a TCP/IP socket, you would call the Socket.socket () function like this: Tcpsock = Socket.socket (socket.af_inet,socket. Socket_stream) UDP/IP Socket udpsock = Socket.socket (socket.af_inet,socket. Socket_dgram) Because there are too many properties in the socket module, we can use the "from module import *" Statement here, we will take all the attributes in the socket module into our namespace. Tcpsock = socket (af_inet,socket_stream)
7. Socket object (built-in) methodFunction Description server-side socket function
- S.bind () Bind address (host name, port number pair) to socket
- S.listen () Start TCP listener
- S.accept () passively accepts TCP client connections, (blocking) waits for a connection to arrive.
Client socket functions
- S.connect () actively initializes the TCP server connection.
- S.CONNECT_EX () connect () extension version, which returns an error code instead of throwing an exception when an error occurs.
Socket functions for public use
- S,RECV () accepts TCP data.
- S.send () sends TCP data.
- S.sendall () sends the TCP data in full.
- S.recvfrom () accepts UDP data.
- S.sendto () sends UDP data.
- S.getpeername () remote address connected to the current socket (TCP connection)
- S.getsockname () The address of the current socket.
- S.getsockopt () returns the parameters of the current socket.
- S.setsockopt () sets the parameters for the specified socket.
- S.close () closes the socket.
module-oriented socket functions
- S.setblocking () sets the blocking and non-blocking mode of the socket.
- S.settimeout () Sets the time-out for blocking socket operations.
- S.gettimeout () Gets the time-out for blocking the socket operation.
File-oriented socket functions
- S.fileno () socket file descriptor.
- S.makefile () Creates a file object associated with the socket.
8.TCP/IP Client and server
&NBSP;TCP Server design pseudo-code: &NBSP;SS = socket () #创建服务器套接字 ss.bind () #把地址绑定到套接字上 ss.listen () &N Bsp #监听连接 inf_loop: &NBS P #服务器无线循环 CS = ss.accept () #接受客户端连接 comm_loop: #通信循环 CS.RECV ()/cs.send () #对话 (Receive and send) cs.close () &NBSP ; #关闭客户端套接字 ss.close () #关闭服务器套接字 (optional) All sockets use the Socket.socket () function To create. The server needs to "sit on a port" to wait for the request. So they have to be "bound" to a local address. A simple (single-threaded) server calls the Accept () function to wait for the connection to arrive. By default, the Accept () function is blocked, that is, the program is in a pending state until the connection arrives. Sockets also support non-blocking states. &NBSP;TCP timestamp server (tstserv.py) creates a message that accepts clients, returns a TCP server from socket After a timestamp is added to the message Import * from time import ctime host = " port = 21567 &nbs P bufsize = 1024 &NBSP;ADDR = (host,port) tcpsersock = socket (af_inet,sock_ STREAM) tcpsersock.bind (ADDR) tcpsersock.listen (5) While true: print ' Waiting for connection ... ' TCPCL ISOCK,ADDR = tcpsersock.accept () print ' ... connected from: ',addr while true:  data = TCPCLISOCK.RECV (bufsiz) &N Bsp if not data: break and nbsp tcpclisock.send (' [%s]%s '% (CTime (), data)) Tcpclisock.close () tcpsersock.close () Create a TCP client pseudo-code: &NBSP;CS = socket () #创建客户端套接字 cs.connect () &NBS P #尝试连接服务器 comm_loop: Cs.send (/CS.R) ECV () #对话 (send/Receive) cs.close () #关闭客 User Socket tcp Timestamp client (tstclnt.py) from socket import * host = ' localhost ' port = 21567 bufsiz = 1024 &NBSP;ADDR = (host,port) tcpclis Ock = socket (af_inet,sock_stream) tcpclisock.connect (ADDR) while True: data = raw_input (' > ') if not data: &N Bsp break tcpclisock.send (data) data = TCPCLISOCK.RECV (bufsiz) If not data: &N Bsp break print data tcpclisock.close ()
9.UDP/IP clients and Servers &NBSP;UDP Timestamp server (tsuserv.py) from socket import * from Time Import ctime host = ' port = 21567 bufsiz = 1024  ; &NBSP;ADDR = (host,port) udpsersock = socket (af_inet,sock_dgram) Udpsersock.bind (ADDR) while true: print ' Waiting for message: .... ' DATA,ADDR = Udpsersock.recvfrom (bufsiz) Udpserso Ck.sendto (' [%s]%s '% (ctime,data), addr) print ' ... received from and returned to: ', a Ddr udpsersock.close () Create a UDP client from socket import * host = ' localhost ' port = ' 21567 ' bufsiz = 1024 &NBSP;ADDR = (HOS T,port) udpclisOck = socket (af_inet,sock_dgram) while trus: data = Raw_input (' > ') If not data: break &N Bsp Udpclisock.sendto (data,addr) DATA,ADDR = Udpclisock.recvfrom ( Bufsiz) If not data: break & nbsp Print data udpclisock.close ()
10.SocketServer ModuleSocketserver is a high-level module in the standard library. Used to simplify the extensive boilerplate code required to implement network clients and servers. In this module, you have implemented some classes that are available for use. Class of the Socketserver module
Class |
Describe |
Baseserver |
Contains Server Core functionality and mixed (mix-in) class hooks; This class is used only for derivation, so instances of this class are not generated; Consider using TCPServer and Udpserver |
Tcpserver/udpserver |
Basic Network Synchronization TCP/UDP Server |
Unixstreamserver/unixdatagramserver |
Basic file-based synchronization TCP/UDP server |
Forkingmixin/threadingmixin |
Implements the core process or threading functionality; As a hybrid class, it is used in conjunction with the server class to provide some asynchronous features; This class is not instantiated directly. |
Threadingtcpserver/threadingudpserver |
Combination of ThreadingMixIn and tcpserver/udpserver |
Baserequesthandler |
Contains core functionality for processing server requests, which are used only for derivation, so instances of this class are not generated to consider using Streamrequesthandler or Datagramrequesthandler |
Streamrequesthandler/datagramrequesthandler |
For TCP/UDP server processing tools |
|
|
Create a SOCKETSERVERTCP server
In the code, first import our server class, and then define the host constants as before. After the host constant is our request processor class, then the boot code. example socketserver timestamp TCP server (tstservss.py) from socketserver import (TCPServer as TCP, Streamrequsethandler as SRH) from time import ctime host = ' &NB Sp PORT = 21567 &NBSP;ADDR = (host,port) class Myrequesthandler (SRH): &NB Sp DEF handle (self): print ' ... connected from: ', SELF.C lient_address self.wfile.write (' [%s]%s '% (CTime (), Self.rfile.readline ())) tcpserv = TCP (addr,myrequesthandler) print ' Waiting for connection ... ' tcpserv.serve_forever () Create SOCKETSERVERTCP client & Nbsp;from Socket Import * host = ' localhost ' port = 21567 bufsiz = 1024 &NBSP;ADDR = (host,port) while true: Tcpclisock = socket (af_inet,sock_stream) Tcpclisock.connect (ADDR) data = raw_input (' > ') If not data: &N Bsp break tcpclisock.send ('%s\r\n '%data) &NB Sp data = TCPCLISOCK.RECV (bufsiz) If not data: &NB Sp break print data.strip () Tcpclisock.close () &nbs p;
11.Twisted Framework IntroductionTwsited is a fully event-driven network framework. It allows you to use and develop fully asynchronous network applications and protocols. Need to install it, the system can have: network protocol, thread, security and authentication, chat/Instant Messaging, database management, relational database integration, web/internet, e-mail, command line parameters, graphical interface integration. Create a twisted Reactor TCP server twsited Reactor event Stamp Server (tstservtw.py) from twisted.internet import Protocol,reactor From time import CTime PORT = 21567 class Tsservprotocol (protocol. Protocol)-----------------------
after-school questions16-1. Sockets, what is the difference between connection-oriented and no-connection? A: The second parameter of the socket is different. The connection-oriented TCP communication function is Socket.socket (socket.af_inet,socket. SOCK_STREAM), the second parameter of a UDP communication function is sock_dgram. 16-2. client/server architecture. Describe the architecture in your own language. And give a few examples? A: The server waits for a client connection on a port. What do you say? client<------------>internet<------------->server16-3. Sockets. In TCP and UDP, which server receives the connection, it gives the connection to different sockets to handle the communication with the client. Answer: TCP. 16-4. Modify the TCP (tstclnt.py) and UDP (tsuclnt.py) clients so that the name of the server is not written in the code, to allow the user to specify a hostname and port, only use the default value when no two values are entered. Answer: 16-5. Network interconnection and sockets. Find the Python Library Reference sample TCP client/server program, implement it and let it run. Run the server first, then the client. Http://www.python.org/doc/current/lib/Socket_Example.html you think this server is too boring, decide to modify the server so that it can recognize the following command: The data server will return its current time, That is, Time.ctime (Time.time ()) OS gets information about the operating system (OS.NAME) LS Gets the list of files in the current directory
Python learning "16" network programming