使用SocketServer创建TCP/UDP同步服务器

2025——》Socket Server 模块简介/Python中使用SocketServer模块的实例代码 Python 的 SocketServer 模块为网络编程提供了便捷的服务器框架,支持 TCP/UDP 协议和多线程/进程处理。该模块包含 TCPServer、UDPServer 等核心组件,以及请求处理器类和并发处理类。通过示例代码展示了创建简单 TCP 服务器、多线程服务器和 UDP 服务器的实现方法,包括对应的客户端测试代码。SocketServer 适合学习网络编程基础和小型应用开发,但对于高并发场景建议使用 asyncio 等现代异步框架。文中提供的代码示例可直接运行,帮助开发者快速掌握该模块的基 阅读详情

为了快速搭建服务器,标准库中有个高级模块SocketServer

它提供了一些可供使用的类(使用类就是会了封装那些繁琐的细节)

我们来看看SocketServer中提供的2个重要的类

  1. TCPServer/UDPServer 网络同步服务器
  2. StreamRequestHandler/DatagramRequestHandler 2种处理器,处理客户请求

注:SocketServer请求处理器的默认行为是:接收连接,得到请求,之后断开连接。也就是说如果一个客户想说好几句话时,必须得说一句,建立一个Socket

本章还提到了“事件驱动”

事件驱动:只有在事件出现的时候,程序才做出反应

什么是事件? 你点击一个按钮,就是触发一个事件,电脑会对此做出反应。发生什么事件就调用相应的函数进行处理,这就是事件驱动。我们可以定义事件类,并在这些类中定义处理器。这样就可以快速的知道是什么事件,进而快速调用相应处理器解决。这也是面向对象的编程思想。

非事件驱动:个人理解是发生一个事件后,程序首先会执行一系列操作来确定这是什么事件,确定下来后才会采用对应的方法进行解决。

下面的实例会实现一个请求处理器,只有当客户提出请求时,就会调用该处理器来处理请求。没有客户接入时,CPU会暂时休息,这样就对CPU进行有效利用。

创建TCP同步服务器

#-*- coding:utf-8 -*-

#导入一个TCP服务器类和一个流处理器(处理TCP请求)
from SocketServer import (TCPServer as TCP, \
                StreamRequestHandler as SRH)
from time import ctime


HOST = 'localhost'
PORT = 20000
ADDR = (HOST, PORT)

class RequestHandler(SRH):
    def handle(self):
        print "...connec
利用Python中SocketServer 实现客户端与服务器间非阻塞通信 利用SocketServer模块来实现网络客户端与服务器并发连接非阻塞socket。 首先,先了解下SocketServer模块中可供使用的类: BaseServer:包含服务器的核心功能与混合(mix-in)类挂钩;这个类只用于派生,所以不会生成这个类的实例;可以考虑使用TCPServer和UDPServer。 TCPServer/UDPServer:基本的网络同步TCP/UDP服务器。 阅读详情

相关推荐

Unity PBR实战:从零打造丝绸材质各向异性高光效果

本文详细介绍了在Unity中实现丝绸材质各向异性高光效果的PBR实战技巧。通过改造Standard Shader、适配IBL环境光以及高级效果调优,开发者可以创建出逼真的丝绸材质,展现动态光纹变化。文章包含关键代码示例和参数配置建议,特别适合需要提升材质表现力的Unity开发者。

weixin_29015483的博客 461

Stata中介效应分析实战:从sgmediation安装到Sobel检验结果解读

本文提供了Stata中进行中介效应分析的完整实战指南,重点介绍了第三方命令sgmediation的安装、配置与使用。通过详细案例演示了如何运用Sobel检验分析变量间的间接效应,并深入解读检验结果,帮助研究者厘清自变量影响因变量的具体路径。文章还探讨了Sobel检验的原理、优缺点及结果报告规范,是进行实证研究的实用参考。

weixin_29197051的博客 631

别只聊天了!手把手教你为Ollama+Open WebUI搭建本地知识库(基于BGE-M3和Qwen)

本文详细介绍了如何利用Ollama、Open WebUI和BGE-M3构建本地知识库,实现智能问答和文档检索。通过环境准备、文档处理、向量化实战和应用案例,帮助用户突破基础聊天场景,打造高效的个人知识管理体系。特别适合技术文档管理和学术研究场景。

weixin_42523720的博客 479

基于深度学习的目标检测在 Android 端的优化实现:YOLO Mobile × NPU 加速实战教程

随着国产手机芯片日益强大,终端侧的目标检测任务已经具备实用性基础。本文围绕实际工程场景,详细讲解如何在 Android 应用中部署轻量级目标检测模型(如 YOLO Mobile、EfficientDet Lite),并结合国产手机 NPU 能力,实现高性能、低延迟、实时目标检测系统。文章将涵盖从模型选择、结构优化、量化转换到 Android 上推理加速、UI 实时渲染的全链路工程路径,强调每一环节的真实可复现性与部署细节,适合 AI 工程师、移动开发者及企业级应用落地团队参考使用。

努力分享一些人工智能、计算机视觉、影像等相关的知识干货! 1410

Open3D 曲率下采样

曲率下采样是一种基于几何特征的点云处理技术,通过计算每个点的曲率来判断其所在位置的局部表面特征,从而进行选择性保留。曲率的计算通常基于点的法向量和其邻域点的分布。

纵马踏花向自由 841

uniapp - 超详细实现播放 svg / svga 格式动画组件插件,用于直播间赠送礼物特效动画或项目动画特效较多的应用(新手小白保姆级教程,提供插件+详细运行示例+使用文档+注意事项+格式说明)

uniappsvga,uniapp播放svga动画,uniapp中使用svga动画详细教程,uniapp播放svga的插件,uniapp有没有调用svga格式动画的组件插件,uinappH5App小程序全端兼容的svga播放器免费好用插件,uniapp好用的svga格式动画插件,在uniapp中使用SVGAPlayer播放svga动画,uniapp中使用svga动画,编译到apph5,uniapp运行svg动画,uniapp怎么使用svga文件格式,uniapp播放svg格式的动画教程,un

🏆 前端领域优质创作者 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

上一篇: UDP服务器和客户端程序实例
下一篇: 数据库基本概念
PythonKidDz
博客等级 码龄10年 7粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值