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 ...
随机推荐
- 利用在线工具自动化生成findviewById
我们在编码的时候经常会用到findviewById,不厌其烦,我之前介绍过一个很取巧的方法,挺好用的,这里再贴一下: public class KaleBaseActivity extends Act ...
- Android 首页图片轮播
1.网络上的的一个框架,已经在github 上开源 github : https://github.com/gcgongchao/flashview 相关博客 : http://www.eoeand ...
- android在Data目录内置可删除的APP
一.准备工作:make_ext4fs.mkuserimg.sh.simg2img,把它们跟要修改的 .img.ext4(或.img)文件放置到同一个目录下 二.转换源文件为img格式( .img则略过 ...
- 用二进制大对象类型Blob实现图片入库与出库的操作
package readclobDemo.bao; import java.io.FileInputStream; import java.io.FileNotFoundException; impo ...
- 弃用的异步get和post方法之代理方法
#import "ViewController.h" #import "Header.h" @interface ViewController () <N ...
- IOS杂笔- 7(类方法load与initialize的区别 浅析)
在介绍两种类方法之前,NSObject Class Reference里对这两个方法说明: +(void)initialize The runtime sends initialize to each ...
- iOS 使用SDwebImage缓存图片并在断网时候显示
[_loadImageView setShowActivityIndicatorView:YES]; [_loadImageView setIndicatorStyle:UIActivityI ...
- win7 解决git clone 连接被拒绝—hosts文件过期
我出现问题的原因是自己修改过 C:\Windows\System32\drivers\etc\HOSTS, 把同事的这个文件拷贝过来后,一切恢复了正常 错误在eclipse中表现为: ...
- 数据库测试DbUnit
DBUnit 的设计理念就是在测试之前,备份数据库,然后给对象数据库植入我们需要的准备数据,最后,在测试完毕后,读入备份数据库,回溯到测试前的状态: 摘自:DbUnit入门实战 DBUnit官网:ht ...
- Weblogic11g下调WebService出现的一系列问题
Weblogic11g下调WebService出现的一系列问题 今天在远程测试机上测试前天写的调用WebService接口方法,遇到的问题还真多啊! 首先说明一下weblogic加载jar包的顺序: ...