Socket Programming in C#--Multiple Sockets
Now lets say you have two sockets connecting to either two different servers or same server (which is perfectly valid) . One way is to create two different delegates and attach a different delegate to different BeginReceive
function. What if you have 3 sockets or for that matter n sockets , this approach of creating multiple delegates does not fit well in such cases. So the solution should be to use only one delegate callback. But then the problem is how do we know what socket completed the operation.
Fortunately there is a better solution. If you look at the BeginReceive
function again, the last parameter is a state is an object. You can pass anything here . And whatever you pass here will be passed back to you later as the part of parameter to the callback function. Actually this object will be passed to you later as a IAsyncResult.AsyncState. So when your callback gets called, you can use this information to identify the socket that completed the operation. Since you can pass any thing to this last parameter, we can pass a class object that contains as much information as we want. For example we can declare a class as follows:
public class CSocketPacket
{
public
System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new
byte[1024];
}
and call BeginReceive
as follows:
CSocketPacket theSocPkt = new CSocketPacket
();
theSocPkt.thisSocket = m_socClient;
// now start to listen for any
data...
m_asynResult = m_socClient.BeginReceive (theSocPkt.dataBuffer
,0,theSocPkt.dataBuffer.Length ,SocketFlags.None,pfnCallBack,theSocPkt);
and in the callback function we can get the data like this:
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState
;
//end receive...
int iRx = 0 ;
iRx =
theSockId.thisSocket.EndReceive (asyn);
char[] chars = new char[iRx +
1];
System.Text.Decoder d =
System.Text.Encoding.UTF8.GetDecoder();
int charLen =
d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String
szData = new System.String(chars);
txtDataRx.Text = txtDataRx.Text +
szData;
WaitForData();
}
catch (ObjectDisposedException
)
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived:
Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
To see the whole application download the code and you can see the code.
There is one thing which you may be wondering about. When you call
BeginReceive
, you have to pass a buffer and the number of bytes to
receive. The question here is how big should the buffer be. Well, the answer is
it depends. You can have a very small buffer size say, 10 bytes long and if
there are 20 bytes ready to be read, then you would require 2 calls to receive
the data. On the other hand if you specify the length as 1024 and you know you
are always going to receive data in 10-byte chunks you are unnecessarily wasting
memory. So the length depends upon your application.
Socket Programming in C#--Multiple Sockets的更多相关文章
- Socket programming in C on Linux | tutorial
TCP/IP socket programming This is a quick guide/tutorial to learning socket programming in C languag ...
- C Socket Programming for Linux with a Server and Client Example Code
Typically two processes communicate with each other on a single system through one of the following ...
- [PHP-Socket] Socket Programming in PHP
Simple Client-Server socket program in PHP Introduction Sockets are used for interprocess communicat ...
- Socket Programming in C#--Getting Started
Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...
- Socket Programming in C#--Introduction
This is the second part of the previous article about the socket programming. In the earlier article ...
- How To: Perl TCP / UDP Socket Programming using IO::Socket::INET
http://www.thegeekstuff.com/2010/07/perl-tcp-udp-socket-programming/ In this article, let us discuss ...
- linux c socket programming
原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...
- TCP Socket Programming in Node.js
TCP Socket Programming in Node.js Posted on October 26th, 2011 under Node.jsTags: Client, node.js, S ...
- Socket Programming in C#--Conclusion
Conclusion And that's all there is to it! Here is how our client looks like Here is how our server l ...
随机推荐
- android assets文件夹资源的访问
1.assets文件夹里面的文件都是保持原始的文件格式 . 2.assets中的文件只可以读取而不能进行写的操作. 3.assets目录下的资源文件不会在R.java自动生成ID,所以读取assets ...
- NSArray数字和排序
1.数字 int main(int argc, const char * argv[]) { @autoreleasepool { //添加空白 [NSNull null] // NSArray *a ...
- 如何改进iOS App的离线使用体验
App Store中的App分析 App已经与我们形影不离了,不管在地铁上.公交上还是在会场你总能看到很多人拿出来手机,刷一刷微博,看看新闻. 据不完全统计有近一半的用户在非Wifi环境打开App,以 ...
- [AapacheBench工具]web性能压力测试工具的应用与实践
背景:网站性能压力测试是性能调优过程中必不可少的一环.服务器负载太大而影响程序效率是很常见的事情,一个网站到底能够承受多大的用户访问量经常是我们最关心的问题.因此,只有让服务器处在高压情况下才能真正体 ...
- JavaScript Patterns 3.7 Primitive Wrappers
Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 1 ...
- git_sop 脚本使用说明
tags : git 前言 脚本下载地址: git是功能非常强大的版本管理工具,同时它带来的是学习成本的上升.最近我们团队的部分项目采用了git进行版本管理,一部分小伙伴对于git使用不是很熟悉.一方 ...
- JS判断浏览器类型及版本
浏览器 ie firefox opera safari chrome 分类: 一路辛酸---JavaScript 你知道世界上有多少种浏览器吗?除了我们熟知的IE, Firefox, Opera, S ...
- fcntl 获取文件状态标志
int fcntl(int fd,int cmd,...) 函数fcntl提供了非常丰富的功能.主要依赖于cmd的各种参数: 复制已有的文件描述符 F_DUPFD,F_DUPFD_CLOEXEC 获取 ...
- AngularJS模块加载
配置块 在模块的加载阶段,AngularJS会在提供者注册和配置的过程中对模块进行配置.在整个AngularJS的工作流中,这个阶段是唯一能够在应用启动前进行修改的部分. angular.module ...
- Linux shell get random number
the Shell Profile: When a new interactive shell is started, /etc/profile, followed by /etc/bash.bash ...