python 网络编程详解及简单实例
作者:lqh 时间:2021-09-02 06:40:56
python 网络编程详解
网络编程的专利权应该属于Unix,各个平台(如windows、Linux等)、各门语言(C、C++、Python、Java等)所实现的符合自身特性的语法都大同小异。在我看来,懂得了Unix的socket网络编程,其他的形式的网络编程方法也就知道了。这句话说得还不太严谨。准确的应该说成懂得了socket编程的原理,网络编程也就知道了,不同之处就在于每个平台,每个语言都有自己专享的语法,我们直接灵活套用就行了。
下面是用python实现的最基本的网络编程的例子,即依托于客户端-服务器的架构,实现客户端与服务器之间的单向“数据流通”。我们分别用两个方法来实现,一个方法是最原始的socket编程,另一个方法是利用python的面向对象对第一种方法进行封装实现,目的是减少实现透明性,便于快速开发。
要求:客户端输入数据,发送到服务端,服务器端生成(时间戳+数据)的封装数据回应客户端。由于socket编程包括两种:面向连接的和无连接的,这两种分别对应TCP数据流和UDP数据报文。所以,我们两种方法都进行实现。
一、Python socket编程
面向连接的TCP socket编程:
# -*- 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()
无连接的UDP socket编程
# -*- 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()
二、基于封装类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 的请求处理器的默认行为是接受连接,
# 得到请求,然后就关闭连接,所以需要多次连接
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()
感谢阅读,希望能帮助大家,谢谢大家对本站的支持!
来源:http://www.cnblogs.com/bakari/p/4213832.html
标签:python,网络编程
0
投稿
猜你喜欢
MyBatis SQL xml处理小于号与大于号正确的格式
2024-01-20 03:32:57
python pdb调试方法分享
2022-02-15 22:39:22
sql查询点滴记录
2012-01-05 19:07:49
Python必知必会之os模块实例详解
2023-06-09 22:31:07
关于CSS中字号控制的兼容性研究
2010-01-23 12:48:00
tensorflow ckpt模型和pb模型获取节点名称,及ckpt转pb模型实例
2021-05-23 10:22:53
Go语言提升开发效率的语法糖技巧分享
2024-05-21 10:22:39
Python3 利用requests 库进行post携带账号密码请求数据的方法
2023-04-03 05:37:53
基于python和flask实现http接口过程解析
2022-06-01 11:46:36
python 实现绘制整齐的表格
2022-09-25 05:51:22
手写Vue2.0 数据劫持的示例
2024-05-22 10:43:17
mysql 5.7.16 安装配置方法图文教程
2024-01-28 14:26:32
支付宝小程序向用户发红包的实现方法
2022-12-19 22:58:58
JavaScript实现获取select下拉框中第一个值的方法
2024-04-22 12:50:05
使用python os模块复制文件到指定文件夹的方法
2022-01-06 13:23:01
MySQL操作符(and、or、in、not)的具体使用
2024-01-17 22:46:44
MySQL的添加用户的两种方法
2012-01-29 17:50:10
python3音乐播放器简单实现代码
2022-06-12 04:43:14
分享python数据统计的一些小技巧
2022-08-20 11:24:47
Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
2022-04-07 09:50:44