Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Python network programming

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Client / server architecture

A server is a series of hardware or software that provides the required 'services' for one or more clients (users of the service). It exists only for the purpose of waiting for requests from clients, responding to them (providing services), and then waiting for more requests. On the other hand, the client contacts the server for a specific request, sends the necessary data, then waits for a response from the server, and finally completes the request or gives fault information. The server runs indefinitely and processes requests constantly, while the client makes an one-time request, then receives the service, and finally ends the transaction between them.

The most common client / server architecture is shown in the figure, which depicts multiple clients retrieving information from a server over the Internet.

Socket is the data structure of computer network, which embodies the concept of "communication endpoint". Before any type of communication can begin, the network application must create a socket. They can be compared to telephone jacks without which communication would be impossible.

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is "everything is a file". Files are operated in open, read-write, and closed modes. Socket is an implementation of this pattern, socket is a special file, and some socket functions operate on it (read / write IO, open, close). There are usually two types of sockets: file-based and network-oriented.

The first type is file-based AF_UNIX, which is mainly used for communication between two processes in the same computer, and the second is network-oriented AF_INET, which is mainly used for communication between computers on the Internet.

Usually, network sockets are divided into connection-oriented sockets and connectionless sockets. Connection-oriented communication provides serialized, reliable, and non-repetitive data delivery without recording boundaries. The main protocol that implements this type of connection is the Transmission Control Protocol (TCP). In order to create a TCP socket, you must use SOCK_STREAM as the socket type.

In contrast to the transmission control protocol is a Datagram-type socket, which is a connectionless socket. This means that there is no need to establish a connection before the communication begins. At this time, the sequence, reliability or repeatability of the data transmission process can not be guaranteed. However, datagrams preserve record boundaries, which means that messages are sent as a whole, rather than divided into multiple fragments. The main protocol that implements this type of connection is the user Datagram (UDP). In order to create a UDP socket, you must use SOCK_DGRAM as the socket type.

Network programming in Python

S=socket (family,type, proto=0)

Parameter 1: address cluster

Socket.AF_INET IPv4 (default)

Socket.AF_INET6 IPv6

Socket.AF_UNIX can only be used for interprocess communication in a single Unix system.

Parameter 2: connection type

Socket.SOCK_STREAM streaming socket, for TCP (default)

Socket.SOCK_DGRAM Datagram socket, for UDP

Socket.SOCK_RAW raw sockets, ordinary sockets can not handle ICMP, IGMP and other network messages, but SOCK_RAW can; secondly, SOCK_RAW can also deal with special IPv4 messages; using raw sockets, users can construct IP headers through the IP_HDRINCL socket option.

Socket.SOCK_RDM is a reliable form of UDP that guarantees delivery of datagrams but not order. SOCK_RAM is used to provide low-level access to the original protocol when some special operations need to be performed, such as sending ICMP messages. SOCK_RAM is usually limited to programs run by advanced users or administrators.

Socket.SOCK_SEQPACKET 's reliable continuous packet service

Parameter 3: protocol

0 (default) A protocol related to a specific address family. If it is 0, the system will automatically select an appropriate protocol according to the address format and socket type.

Server socket method

S.bind (address) binds the socket to the address. The format of the address address depends on the address family. Under AF_INET, addresses are represented as tuples (host,port). S.listen (backlog) starts listening for incoming connections. Backlog specifies the maximum number of connections that can be suspended before denying connections. 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 address where the client is connected. Receive the connection from the TCP customer (blocking) waiting for the connection to arrive

Client socket method

S.connect (address)

Connect to the socket at address. The format of address is tuple (hostname,port). If there is an error in the connection, an socket.error error is returned.

S.connect_ex (address) is the same as above, except that there is a return value, which returns 0 when the connection succeeds and encodes when the connection fails, instead of throwing an exception.

Common socket method

S.recv (bufsize [, flag]) receives data from the socket. The data is returned as a string, and the bufsize specifies the maximum number that can be received. Flag provides additional information about the message, which can usually be ignored. S.recv_into ()

Receives TCP messages to the specified cache. Sk.recvfrom (bufsize [.flag]) is similar to recv (), but the return value is (data,address). Where data is the string containing the received data and address is the socket address where the data is sent. S.send (string [, flag]) sends data from string to the connected socket. The return value is the number of bytes to be sent, which may be less than the byte size of string. That is, the specified content may not be all sent. S.sendall (string [, flag])

Sends data from string to the connected socket, but attempts to send all data before returning. None is returned for success, and an exception is thrown for failure. Internally through a recursive call

Send, send out all the content.

S.sendto (string [, flag], address) sends data to the socket, where address is a tuple in the form (ipaddr,port) that specifies the remote address. The return value is the number of bytes sent. This function is mainly used for the UDP protocol. S.close () closes the socket s.getpeername () and returns the remote address of the connection socket. The return value is usually a tuple (ipaddr,port) s.getsockname () that returns the socket's own address. Usually a tuple (ipaddr,port)

Blocking-oriented socket method

Whether s.setblocking (bool) is blocked (the default True). If False is set, an error will be reported when accept and recv have no data. S.settimeout (timeout)

Sets the timeout period for socket operations, where timeout is a floating-point number in seconds. The value is

None says there is no timeout. In general, the timeout period should be set when the socket is first created, as they may be used for connection operations (for example, client connections wait up to 5 seconds)

S.gettimeout () gets the timeout of the blocking socket operation

File-oriented socket method

The file descriptor s.makefile () of the s.fileno () socket

Create a file object associated with a socket

Create TCP server and client

Server side:

#! / usr/bin/env python#-*-coding:utf-8-* -''this script creates a TCP server, which receives messages from the client, prints them on the terminal, and returns 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,PORT) 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 print (str (data,'utf-8')) tcpCliSock.close ()

Running result:

Server side:

Waiting for connection.connected from: ('127.0.0.1 percent, 62735) 1231234345345567

Client:

> 123Sat May 6 21:31:06 2017 > 1234Sat May 6 21:32:44 2017 > 3453Sat May 6 21:32:46 2017 > 45Sat May 6 21:32:47 2017 > 567Sat May 6 21:32:48 2017 >

Create UDP client and server

Server side:

#! / usr/bin/env python#-*-coding:utf-8-*-from socket import * from time import ctime''' this script creates a UDP server, receives messages from the client and prints them on the terminal, and returns the current timestamp''HOST =' 'PORT = 12345BUFSIZ = 1024ADDR = (HOST,PORT) udpSerSock = socket (AF_INET,SOCK_DGRAM) udpSerSock.bind (ADDR) while True: print (' waiting for message...') Data,addr = udpSerSock.recvfrom (BUFSIZ) print (str (data,'utf-8')) udpSerSock.sendto (bytes (ctime (), 'utf-8'), addr) print ('... received form and return to:',addr) udpSerSock.close ()

Client:

#! / usr/bin/env python#-*-coding:utf-8-*-from socket import * HOST = 'localhost'PORT = 12345BUFSIZ = 1024ADDR = (HOST,PORT) udpCliSock = socket (AF_INET,SOCK_DGRAM) while True: data=input (>') if not data: break udpCliSock.sendto (bytes (data,'utf-8'), ADDR) data,ADDR=udpCliSock.recvfrom (BUFSIZ) if not data: break print (str (data) 'utf-8')) udpCliSock.close ()

Output result:

Server side:

Waiting for message... 123...received form and return to: ('127.0.0.1 percent, 58765) waiting for message... 12334...received form and return to: ('127.0.0.1 percent, 58765) waiting for message... 123...received form and return to: ('127.0.0.1 percent, 58765) waiting for message... 14...received form and return to: ('127.0.0.1 percent, 58765) waiting for message... 234...received form and return to: ('127.0.0.1 percent, 58765) waiting for message... 5...received form and return to: ('127.0.0.1 percent, 58765) waiting for message...

Client:

> 123Sun May 7 11:59:46 2017 > 12334Sun May 7 12:02:32 2017 > 1231Sun May 7 12:02:33 2017 > 42Sun May 7 12:02:34 2017 > 34Sun May 7 12:02:34 2017 > 5Sun May 7 12:02:35 2017 >

SocketServer module

SocketServer is an advanced module in the standard library, which aims to simplify a lot of boilerplate code, which is necessary to create network clients and servers. There are a variety of classes in this module that help programmers hide specific implementation details, in addition to handling transactions as face-to-face objects to help organize data and logically put functions in the right place. In python3, SocketServer is renamed to socketserver.

Inheritance relationships between classes:

| | BaseServer | v | TCPServer |-> | UnixStreamServer | | v | UDPServer |-> | UnixDatagramServer |

Class description

BaseServer

Contains hooks for core server functions and mix-in classes, for derivation only, so that no instance of this class is created: you can create an instance of the class with TCPServer or UDPServer. TCPServer/UDPServer is based on a network synchronization TCP/UDP server.

UnixStreamServer /

UnixDatagramServer

File-based basic synchronization TCP/UDP server

The above four service classes process requests synchronously, that is, one request cannot be processed until the next request is processed. When you want to support the asynchronous model, you can use multiple inheritance to have the server class inherit from the ForkingMixIn or ThreadingMixIn class.

Class description

ForkingMixIn/

ThreadingMixIn

Core dispatching or threading function: only use a server class in the mix-in class domain to achieve some asynchrony; it cannot be instantiated directly.

ForkingTCPServer/

ForkingUDPServer

The combination of ForkingMixIn and TCPServer/UDPServer, using multi-process to realize asynchronous ThreadingTCPServer/

ThreadingUDPServer

The combination of ThreadingMixIn and TCPServer/UDPServer, using multithreading to realize async

In the SocketServer module, the server handles requests mainly through the BaseRequestHandler class, where multiple handlers can be used.

Setup ()

The requested initialization action is called before the handle () method, and no action is performed 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

Client address through the self.client_address function

The server instance uses the self.server function

Self.request is a socket object for streaming service self.request and a series of strings and sockets for Datagram self.request.

Finish ()

Call this method after the handle () function to perform the cleanup operation after the request. No action is performed by default. If an exception occurs in setup (), this function will not be called.

Server-side instance:

#! / usr/bin/env python#-*-coding:utf-8-*''through the socketserver class, TCPServer and StreamRequestHandler, the script creates a timestamp TCP server' from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH) from time import ctimeHOST =''PORT = 12345ADDR = (HOST,PORT) class MyRequestHandler (SRH): def setup (self): print (' before processing the request!') Def handle (self): conn=self.request print ('... connected from:',self.client_address) print (str (conn.recv (1024),' utf-8')) conn.send (bytes (ctime (), 'utf-8')) def finish (self): print (' after processing the request!') Print ('-') tcpServ = TCP (ADDR,MyRequestHandler) print ('waiting for connection...') tcpServ.serve_forever ()

Client instance:

#! / usr/bin/env python#-*-coding:utf-8-*-from socket import * HOST = 'localhost'PORT = 12345BUFSIZ = 1024ADDR = (HOST,PORT) while True: tcpCliSock = socket (AF_INET,SOCK_STREAM) tcpCliSock.connect (ADDR) data=input (>') if not data: break tcpCliSock.send (bytes (data,'utf-8')) data=tcpCliSock.recv (BUFSIZ) if not data: break print (str (data) 'utf-8')) tcpCliSock.close ()

Running result:

Server side:

Waiting for connection... Before processing the request! ... connected from: ('127.0.0.1 requests, 62042) 1223 after processing the request! Before processing the request! ... connected from: ('127.0.0.1 requests, 62051) 123 after processing the request! Before processing the request! ... connected from: ('127.0.0.1 requests, 62052) 5435 after processing the request! Before processing the request! ... connected from: ('127.0.0.1 requests, 62053) 574After processing the request! Before processing the request! ... connected from: ('127.0.0.1 requests, 62054) 68 after processing the request! --

Client:

> 1223Sun May 7 13:01:45 2017 > 123Sun May 7 13:01:46 2017 > 5435Sun May 7 13:01:47 2017 > 574Sun May 7 13:01:48 2017 > 68Sun May 7 13:01:49 2017 >

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report