python network programming details and simple examples
- 2020-05-30 20:32:55
- OfStack
python network programming details
The patent right for network programming should belong to Unix, and the syntax that each platform (windows, Linux, etc.) and language (C, C++, Python, Java, etc.) implements in accordance with its own characteristics is much the same as that of the language (C, C++, Python, Java, etc.). In my opinion, if you know Unix's socket network programming, you will also know other forms of network programming methods. This is not a very precise statement. If you know the principle of socket programming, you will know the network programming. The difference is that each platform and language has its own exclusive grammar, which we can apply flexibly.
The following is an example of the most basic network programming implemented with python, which is to realize the one-way "data flow" between the client and the server based on the client-server architecture. We use two methods to achieve this, one is the original socket programming, and the other is the use of python object-oriented method to encapsulate the implementation of the first method, in order to reduce the transparency of the implementation and facilitate rapid development.
Requirements: the client enters data, sends it to the server, and the server generates (timestamp + data) encapsulated data in response to the client. Since there are two types of programming in socket: connection-oriented and connectionless, these two correspond to TCP data streams and UDP datagram, respectively. So, we implement both.
1. Python socket programming
Connection-oriented TCP socket programming:
# -*- coding: utf-8 -*-
3 from socket import *
from time import ctime
# Address and Port
HOST = ''
PORT = 21567
ADDR = (HOST, PORT)
# BuffSize
BUFSIZ = 1024
# build socket
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# bind socket
tcpSerSock.bind(ADDR)
# listen 5 client
tcpSerSock.listen(5)
try:
while True:
print 'waiting for connection...'
# build client socket
tcpCliSock, addr = tcpSerSock.accept()
print '...connect from:', addr
# accept data and process
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (ctime(), data))
# close client socket
tcpCliSock.close()
except EOFError, KeyboardInterrupt:
tcpSerSock.close()
# -*- coding:utf-8 -*-
from socket import *
# Address and Port
HOST = '127.0.0.1'
PORT = 21567
ADDR = (HOST, PORT)
# BufferSize
BUFSIZ = 1024
#build socket
tcpCliSocket = socket(AF_INET, SOCK_STREAM)
tcpCliSocket.connect(ADDR)
while True:
data = raw_input('> ')
if not data:
break
# send data
tcpCliSocket.send(data)
# recv data
data = tcpCliSocket.recv(BUFSIZ)
if not data:
break
# show data
print data
tcpCliSocket.close()
Connectionless UDP socket programming
# -*- coding: utf-8 -*-
from socket import *
from time import ctime
# Address and Port
HOST = ''
PORT = 8000
ADDR = (HOST, PORT)
# BufferSize
BUFFSIZE = 1024
# build socket
udpSerSock = socket(AF_INET, SOCK_DGRAM)
# bind socket
udpSerSock.bind(ADDR)
try:
while True:
print 'waiting the message...'
data, addr = udpSerSock.recvfrom(BUFFSIZE)
print 'received the message: '+data+' from: ', addr
udpSerSock.sendto('[%s] %s' % (ctime(), data), addr)
except EOFError, KeyboardInterrupt:
udpSerSock.close()
# -*- coding: utf-8 -*-
from socket import *
# Address and Port
HOST = 'localhost'
PORT = 8000
ADDR = (HOST, PORT)
# BufferSize
BUFSIZ = 1024
# build socket
udpCliSock = socket(AF_INET, SOCK_DGRAM)
while True:
data = raw_input('> ')
udpCliSock.sendto(data, ADDR)
data = udpCliSock.recvfrom(BUFSIZ)
if not data:
break
print data
udpCliSock.close()
2. Network programming based on encapsulation class SocketServer
# -*- coding: utf-8 -*-
from SocketServer import TCPServer as TCP, StreamRequestHandler as SRH
from time import ctime
# Address and Port
HOST = ''
PORT = 21567
ADDR = (HOST, PORT)
# BuffSize
BUFSIZ = 1024
# build RequestHandler
class MyRequestHandler(SRH):
def handle(self):
print '...connected from: ', self.client_address
self.wfile.write('[%s] %s' % (ctime(), self.rfile.readline()))
# build TCPServer
TCPServ = TCP(ADDR, MyRequestHandler)
print 'waiting for connection...'
# loop to process
TCPServ.serve_forever()
# -*- coding:utf-8 -*-
from socket import *
# Address and Port
HOST = '127.0.0.1'
PORT = 21567
ADDR = (HOST, PORT)
# BufferSize
BUFSIZ = 1024
while True:
# note: SocketServer The default behavior of the request handler is to accept the connection,
# You get the request, and then you close the connection, so you need multiple connections
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
# process data
data = raw_input('> ')
if not data:
break
tcpCliSock.send('%s\r\n' % data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print data.strip()
tcpCliSock.close()
Thank you for reading, I hope to help you, thank you for your support of this site!