Python Network programming

Source: Internet
Author: User

Before starting the Python network programming, the first thing to know about sockets, sockets is a computer network data structure. There are two types of sockets, namely, file-based and network-based, the former such as Af_unix, the latter such as Af_inet, Af_netlink. The socket port, like the telephone number, is the unique identity of the communication identity, the legal port number range is 0 to 65535, where the port number less than 1024 is the system reserved port, if the UNIX operating system, the reserved port number can be obtained through the/etc/services file.

There are two types of sockets, connection-oriented sockets and non-connected sockets. The former provides sequential, reliable, not duplicate data transmission, but also does not add a boundary, each message to be sent may be split into multiple copies, the main protocol to achieve this connection is the Transmission Control protocol TCP, socket type sock_stream, using IP to find the host in the network, This creates the entire system. No connected sockets, the order of data arrival, reliability and data is not guaranteed, the datagram will retain data boundaries, send messages will not be split into small pieces, although there are so many shortcomings, but it is not connected, so do not have to bear the burden of maintaining the virtual circuit connection, better performance, The primary protocol for this connection is User Datagram Protocol UDP, socket type sock_dgram, and IP to find hosts in the network.

Python network programming uses the socket module, which creates sockets with its socket () function, with the following syntax:
Socket (socket_family, socket_type, protocol = 0)
Socket_family can be Af_unix or af_inet,socket_type can be sock_stream or sock_dgram,protocol generally not written, default is 0.

After we have created the socket, all of the interactions are made through the method calls to the socket object, and some of the common functions of the socket object are listed below.
Server-side-
Bind (): Binds the address to the socket.
Listen (): Start TCP listener.
Accept (): passively accepts TCP client connections, blocking waits for a connection to arrive.
Client--
Connect (): Proactively initialize TCP server connections.
CONNECT_EX (): An extended version of the previous function that returns an error code instead of throwing an exception when an error occurs.
Public use--
Recv (): Receives TCP data.
Send (): Sends the TCP data.
Sendall (): Complete sending of TCP data.
Recvfrom (): Receive UDP data.
SendTo (): Sends UDP data.
Getpeername (): The address of the remote connection to the current socket.
GetSockName (): The address of the current socket.
GetSockOpt (): Returns the parameters for the specified socket.
SetSockOpt (): Sets the parameters for the specified socket.
Close (): Closes the socket.
Blocking related--
Setblocking (): Sets the blocking and non-blocking mode for sockets.
SetTimeout (): Sets the time-out for blocking socket operations.
Gettimetout (): Gets the timeout period for blocking socket operations.
FILE-oriented--
Fileno (): The file descriptor for the socket.
Makefile (): Creates a file associated with the socket.

The following is the pseudo-code of the TCP server--

socket()#创建服务器套接字ss.bind()#把地址绑定到套接字上ss.listen()#监听连接inf_loop:#服务器无限循环        cs = ss.accept()#接收客户的连接    comm_loop:#通讯循环        cs.recv()/cs.send()#对话,接收与发送    cs.close()#关闭客户套接字ss.close()#关闭服务器套接字,可选

Here is the pseudo-code for the TCP client--

socket()#创建客户套接字cs.connect()#尝试连接服务器comm_loop:#通讯循环    cs.send()/cs.recv ()#对话,发送与接收cs.close()#关闭客户套接字

The following is a simple example, the server, the client on the same machine, the server acts as a timestamp role, the client sends the data and returns a time with the same data.
timeserver.py--

#!/usr/bin/env pythonFromSocketImport * FROM TimeImport CTime HOST ="' # any availablePORT =21567 # UnusedBUFSIZE =1024x768ADDR = (HOST, PORT) Tcpsersock =Socket(Af_inet, Sock_stream) tcpsersock.Bind(ADDR) Tcpsersock.Listen(5)# max concurrence access whileTrue:Print ' Waiting for connection ... 'Tcpclisock, addr = Tcpsersock.Accept()# blocking and passive    Print ' ... connected from: ', addr whileTrue:data = Tcpclisock.recv(BUFSIZE)if  notData BreakTcpclisock.Send(' [%s]%s ' %(CTime (), data) Tcpclisock.Close() Tcpsersock.Close()# Optional and never exec

timeclient.py--

#!/usr/bin/env python fromSocket Import *HOST= ' localhost ' # Local HostPORT=21567# the same port asThe serverBUFSIZE=1024x768 ADDR= (HOST,PORT)TC#!/usr/bin/env python fromSocket Import *Pclisock= Socket (af_inet,Sock_stream)Tcpclisock. Connect (ADDR) while True: Data = raw_input(' > ')     ifNot data:Break Tcpclisock.send ( data)     Data = Tcpclisock.recv(BUFSIZE)     ifNot data:Break Print Data Tcpclisock. Close ()

UDP is relatively simple compared to TCP, because it is not connected, so the server does not need listen and accept, the client does not need connect.
The following is the pseudo-code of the UDP server--

ss = socket()ss.bind()#把地址绑定到套接字上inf_loop:#服务器无限循环    cs.recvfrom()/cs.sendto()#对话,接收与发送ss.close()#关闭服务器套接字,可选

The following is the pseudo-code of the UDP client--

cs = socket()#创建客户套接字comm_loop:#通讯循环    cs.sendto()/cs.recvfrom ()#对话,发送与接收cs.close()#关闭客户套接字

The Socketserver module is a high-level socket communication module based on the socket module, which supports the processing of client requests in new threads or processes. This module is a high-level module in the standard library that simplifies the implementation of network clients and servers, and has implemented a number of classes that are available for use in the module. The following example is implemented with Socketserver, the timestamp server.
timessser.py--

#!/usr/bin/env python fromSocketserverImport(TCPServer asTCP, Streamrequesthandler asSRH) fromTimeImportCTime HOST ="'PORT =21567ADDR = (HOST, PORT) class myrequesthandler(SRH):      def handler(self):         Print ' ... connected from: ', Self.client_address Self.wfile.write (' [%s]%s ')% (CTime (), Self.rfile.readline ()) Tcpserv = TCP (ADDR, Myrequesthandler)Print ' Waiting for connection ... 'Tcpserv.serve_forever ()

timesscli.py--

#!/usr/bin/env python fromSocket Import *HOST= ' localhost 'PORT=21567 BUFSIZE=1024x768 ADDR= (HOST,PORT) while True: Tcpclisock = socket (af_inet,Sock_stream) # Socket every time Tcpclisock.connect (ADDR) Data = raw_input(' > ')     ifNot data:Break Tcpclisock.send ('%s\r\n '% data)     Data = Tcpclisock.recv(BUFSIZE)     ifNot data:Break Print data. Strip() Tcpclisock.close ()

Other--
The twisted module is a fully event-driven network framework that can be used to develop completely heterogeneous Web applications and protocols to create a complete system that can have network protocols, threads, security certifications, instant Messaging, database management, Web pages, e-mail, command line parameters, and graphical interface integration. The following uses the twisted module to implement the same functionality as in the above example.
timetsser.py--

#!/usr/bin/env python fromTwisted.internetImportProtocol, reactor fromTimeImportCTime PORT =21567  class tsservprotocol(protocol. Protocol):      def connectionmade(self):SELF.CLNT = Self.transport.getPeer (). HostPrint ' ... connected from: ', SELF.CLNT def datareceived(self, data):         Print ' ... received from [%s]\n\t%s '% (self.clnt, data) Self.transport.write (' [%s]%s '% (CTime (), data)) Factory = protocol. Factory () Factory.protocol = TsservprotocolPrint ' Waiting for connection ... 'Reactor.listentcp (PORT, Factory) Reactor.run ()

timetscli.py--

#!/usr/bin/env python fromTwisted.internetImportProtocol, Reactor HOST =' localhost 'PORT =21567  class tsclntprotocol(protocol. Protocol):      def senddata(self):data = Raw_input (' > ')ifDataPrint ' ... sending%s ... '%data self.transport.write (data)Else: Self.transport.loseConnection () def connectionmade(self):Self.senddata () def datareceived(self, data):         PrintData Self.senddata () Factory = protocol. Clientfactory () Factory.protocol = Tsclntprotocol reactor.connecttcp (HOST, PORT, Factory) Reactor.run ()

The Asyncore/asynchat module provides the underlying functionality for network applications that can handle client requests asynchronously.
Select module, which manages multiple socket connections in a single-threaded network server program.

Python 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.