非阻塞方式下Socket读取数据的一个例子

非阻塞Socket类实战:20150331 本文还有配套的精品资源,点击获取 简介:非阻塞Socket类是一种高效的网络通信方式,允许程序在等待数据传输时执行其他任务。本课程设计项目经过测试,旨在帮助学生掌握非阻塞Socket类的实际应用,包括TCP和UDP通信,以及使用选择器、缓冲区和SocketIO接口进行编程。学生将通过实践任务,提升在网络编程方面的能力,为未来在高并发、低延迟应用开发中打下坚实基础。 1... 阅读详情

 

标题:非阻塞方式下Socket读取数据的一个例子
作者:DreamTiger发表时间:2000-1-15 下午 05:59:13
发信人: lBlade (刀锋), 信区: Delphi       标  题: Re: 斑竹帮忙看看偶这段Socket程序!救救我! (转载)发信站: BBS 水木清华站 (Tue Jan 11 14:22:56 2000)【 在 windlike (风花雪月) 的大作中提到: 】: 多谢指教!: 我去大富翁看了。其中有这么一端:: 阻塞方式可以产生OnClientRead(Write)事件: 而非阻塞方式,需要自己去读。不会产生这些事件: 请问,是这样的吗?如果是,那么如何知道有数据: 到达呢?: 偶的Server肯定要用stThreadBlocking: 谢谢的确如此。在Block方式下,可以通过Windows消息机制进行事件处理,但在NonBlock方式下,读写操作都必须自己手动处理。可以看看下面的示例程序。(一个简单的文件服务器,客户端发送文件名到Server上,Server读取文件名后把Server上的该文件内容发送到客户端)定义一个TFileServerThread线程类,重载其ClientExecute方法。在ServerSocket的GetThread事件中创建出一个新线程进行处理。procedure TForm1.ServerSocketGetThread(Sender: TObject;  ServerSocket: TServerClientWinSocket;  var SocketThread: TServerClientThread);begin  // Create a new thread for connection  SocketThread := TFileServerThread.Create(False, ServerSocket);end;有关TFileServerThread的定义和ServerExecute过程实现如下:(可以通过SocketStream.WaitForData(时间长度)进行数据等待)  TFileServerThread = class(TServerClientThread)  public    procedure ServerExecute; override;  end;procedure TFileServerThread.ServerExecute;var  Data: array[0..1023] of char;  FileName: String;  SocketStream: TWinSocketStream;begin  while not Terminated and ServerSocket.Connected do  try    SocketStream := TWinSocketStream.Create(ServerSocket, 60000);    try      FillChar(Data, SizeOf(Data), 0);      if SocketStream.Read(Data, SizeOf(Data)) = 0 then      begin        // If we didn't get any data after 60 seconds then close the connection        ServerSocket.Close;        Terminate;      end;      FileName := Data;      if Length(FileName) > 2 then        Delete(FileName, Pos(#13#10, FileName), 2);  // Delete #13#10      if FileExists(FileName) and ServerSocket.Connected then      begin        ServerSocket.SendStream(TFileStream.Create(FileName, fmOpenRead or          fmShareCompat or fmShareDenyNone));        // Need to use SendMessage here otherwise S could change        SendMessage(Form1.Listbox1.Handle, LB_ADDSTRING, 0, Integer(PChar(FileName)));        // PostMessage here is OK because we are not relying on any data        PostMessage(Form1.Handle, CM_INCCOUNT, 0, 0);      end;    finally      SocketStream.Free;    end;  except    HandleException;  end;end;



ZYNQ实战:如何用AXI-stream FIFO解决跨时钟域数据同步难题(附完整代码) 本文深入探讨了在ZYNQ项目中,如何利用AXI-Stream FIFO有效解决PS与PL之间的跨时钟域数据同步难题。文章详细分析了异步FIFO的架构设计、关键配置参数,并提供了PS端软件策略与PL端逻辑设计的完整代码示例,旨在帮助开发者构建稳定可靠的数据流通道,优化系统性能。 阅读详情

相关推荐

Zlib1.2.11源码编译(Win10+VS2019)

下载 下载网址: zlib Home Site 得到文件: 解压缩到“D:\SourceCodes\zlib-1.2.11” 使用CMake配置、生成并打开项目 将CMakeLists.txt拖入CMake,配置(Configure): 生成(Generate) 打开项目(Open Project),CMake调用VS2019打开项目 生成debug版本 构建项目ALL_BUILD。成功生成debug版本 在“D:\Sourc...

Alexabc3000的专栏 1905

socket阻塞与非阻塞读写

网络协议一般都是由head和body构成。 socket在实际应用中有2种方式,阻塞和非阻塞。 使用setsockopt()可以在2种方式之间切换。 /** * * 设置非阻塞模式(for Win32) * **/ int nNonBlocking = 1; ioctlsocket(sockListen,FIONBIO,&nNonBlocking); 先看阻塞

开心乐源的专栏 3717

电流互感器的使用分析

有关电流互感器使用的注意事项,回头再看,耳目一新。

qq_46757048的博客 2万+

linux网络编程:设置非阻塞socket收发数据

非阻塞式I/O包括非阻塞输入操作,非阻塞输出操作,非阻塞接收外来连接,非阻塞发起外出连接。包括的函数有:read, readv, recv, recvfrom, recvmsg, write, writev, send, sendto, sendmsg, accept。     将socket 设置为非阻塞模式有三种方法

bian1029的专栏 4535

避坑指南:vue-print-nb打印隐藏元素与空白页的那些事儿

本文深入解析了使用vue-print-nb插件时,打印出现空白页及隐藏元素问题的根本原因与解决方案。核心在于理解浏览器打印原理,并通过CSS媒体查询精准控制样式。文章提供了从重置根元素高度、处理隐藏元素到控制分页的完整避坑指南,帮助开发者彻底解决打印样式难题。

weixin_29008691的博客 445

逆向攻防世界CTF系列40-ReverseMe-120

注意sub_401000main中只传了两个参数,但是跟进后发现四个(可能是隐式传递,放在寄存器里传递了),调试发现a4是输入长度,与最终的you_know_how_to_remove_junk_code比较的是v12(但是并没有被传入),开始怀疑是不是隐式传递了。_mm_xor_si128用于计算128位(16字节)的按位异或,然后通过v14控制循环结束的条件,可以看到v14增长的步长为16,而且通过上面得到的flag值解码得到的字符串为32个字节大小,正好是16的整数倍。

LH1013886337的博客 1421

socket实现非阻塞网络通信实现

一、select函数 select() 可以阻塞地同时探测一组支持非阻塞的 I / O 设备是否有事件发生(如可读,可写,出现异常等等),直至某一个设备触发了事件或者超过了指定的等待时间。此时我们可以把需要的数据源通道放到 select 的探测范围内,只要相应的数据源准备好 select 就会返回,这时就能无阻塞地读取到数据。 select()函数原型及介绍如下所示 int select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* erro

貌似稿手的博客 1247

多模态大模型:基础架构

多模态大型语言模型(MLLM)是人工智能领域的前沿创新,它结合了语言和视觉模型的功能,可以处理复杂的任务,如视觉问答和图像字幕。这些模型利用大规模预训练,集成了多种数据模态,以显著提高其在各种应用程序中的性能。

鲁班模锤 3983

使用socket客户端实现非阻塞收发数据

【代码】使用socket客户端实现非阻塞收发数据。

qq_42207775的博客 490

Mybatis Provider注解实现批量插入

需求 借助mybatis 的provider实现一个比较通用的,批量插入数据接口。 Mapper接口 第一参数为需要批量插入的数据,第二个参数为对应实体类的class public interface BaseDao<T> { @InsertProvider(type = BaseProvider.class, method = "batchInsert") int batchInsert(@Param("lists") List<T&gt

小楼夜听雨的博客 2424

【Dify(v1.x) 核心源码深入解析】File 模块

文件模型(File Model)定义了文件的核心属性,如文件类型、传输方法、相关标识符等,是整个文件处理流程的数据基础。文件解析器(UploadFileParser)负责解析上传的文件,根据配置决定以何种方式(URL 或 Base64)提供图像数据。工具文件解析器(ToolFileParser)专注于工具文件的管理,提供工具文件管理器的获取接口。签名验证与生成(helpers.py)包含文件 URL 签名的生成与验证逻辑,确保文件访问的安全性。文件管理器(file_manager.py)

679

socket阻塞和非阻塞有哪些影响

socket阻塞和非阻塞有哪些不同

mayue_web的博客 3万+

2026年3月GESP真题及题解(C++七级): 选择题和判断题(题解)

2026年3月GESP真题及题解(C++七级): 选择题和判断题(题解)

王老师青少年编程 1006

linux c实现超时、非阻塞socket的函数select

linux c实现超时、非阻塞socket的函数select Select在Socket编程中还是比较重要的,可是对于初学Socket的人来 说都不太爱用Select写程序,他们只是习惯写诸如 connect、accept、recv或recvfrom这样的阻塞程序(所谓阻塞方式block,顾名思义,就是进程或是线程执行到这些函数时必须等  待某个事件的发生,如果事件没有

tjssehaige的专栏 1万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

深度学习工具包 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")

java NIO非阻塞方式的Socket编程

1.非阻塞方式的Socket编程: 传统阻塞方式的Socket编程,在读取或者写入数据时,TCP程序会阻塞直到客户端和服务端成功连接,UDP程序会阻塞直到读取到数据或写入数据。阻塞方式会影响程序性能,JDK5之后的NIO引入了非阻塞方式的Socket编程,非阻塞方式的Socket编程主要是使用Socket通道和Selector通道选择器,将Socket通道注册到通道选择器上,通过通道选择器选...

wangqiaowqo的专栏 113

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

Java 非阻塞 socket 通信

前几天我们公司C语言组的人需要一个基于socket的报文接收器来方便他们测试项目,我花了小半天给他们做了个多线程的socket服务端,我写好后在本机上测试后交给了他们,但是他们那边能连上服务器端,但是发送消息时没响应,后来我看到他们用的都是tcp/ip测试工具(一个c/s结构的socket调试工具)来测了,发送时我的后台也没有收到请求报文,但是他们的连接断了之后 我这边就收到了,又谷歌了一下,还真

chenjizone的专栏 1856

IEM模型,地表粗糙度模拟

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

socket设置为非阻塞模式

1,套接字的默认状态是阻塞的。即当发出一个不能立即完成的套接字调用时,该进程将被投入睡眠,等待相应操作完成。2,阻塞的套接字分为下面四类:输入操作:包括read、recv、recvfrom和recvmsg。输出操作:包括write、send、sendto和sendmsg。接受外来连接,accept 函数。发起外出连接,connect 函数。3,将一个socket 设置成非阻塞模式,使用fcntl...

sanliangGoGoGo 1万+
上一篇: 基于WinSocket的网络通信实现
下一篇: 用Socket接口实现网络异步通信
techweb
博客等级 码龄19年 226粉丝 3842原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址