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 ...
随机推荐
- 无需cygwin,使用NDK进行开发
NDK从7开始自带编译器,在windows上无需配置cygwin的环境. 在eclips中配置NDK路径 在eclipse中点击菜单栏window-Perferences,配置NDK的路径. 在工程中 ...
- UIWebView的简单使用
在iOS9.0之后需要在ifo.plist文件中添加一个配置文件,不然只能识别https开头的网址,http开头的不识别 主要有三个步骤 // 1.获取URL NSURL *url = [NSURL ...
- iOS:交换Button中图片与文字的左右位置
titleEdgeInsets属性和 imageEdgeInsets属性只是在画这个button出来的时候用来调整image和label位置的属性,并不影响button本身的大小.它们只是image和 ...
- IOS学习资源收集--关于动画的代码学习资源总汇(很棒的动画效果哦)
目录大纲: 1.很棒的iOS加载动画. github网址:https://github.com/NghiaTranUIT/FeSpinner 游老师的译文blog:http://www.cnblogs ...
- Eclipse 导入项目后启动报异常:java.lang.UnsatisfiedLinkError: Native Library *.dll already loaded in another classloade 解决方法
tomcat 服务器的配置信息如下:
- mysql 批量更新与批量更新多条记录的不同值实现方法
批量更新 mysql更新语句很简单,更新一条数据的某个字段,一般这样写: 代码如下: UPDATE mytable SET myfield = 'value' WHERE other_field = ...
- 记录ConcurrentHashMap的锁分离技术
对比上图,HashTable实现锁的方式是锁整个hash表,而ConcurrentHashMap的实现方式是锁桶(简单理解就是将整个hash表想象成一大缸水,现在将这大缸里的水分到了几个水桶里,has ...
- 利用JS实现手机访问PC网址自动跳转到wap网站
方法一:使用百度siteapp中的js进行判断 <script src="http://siteapp.baidu.com/static/webappservice/uaredirec ...
- Effective Java 48 Avoid float and double if exact answers are required
Reason The float and double types are particularly ill-suited for monetary calculations because it i ...
- Effective Java 56 Adhere to generally accepted naming conventions
Typographical naming conventions Identifier Type Type Examples Package com.google.inject, org.joda.t ...