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 AsyncTask 只能在线程池里单个运行的问题
android 的AysncTask直接调用Execute会在在一个线程池里按调用的先后顺序依次执行. 如果应用的所有网络获取都依赖这个来做,当有一个网络请求柱塞,就导致其它请求也柱塞了. 在3.0 ...
- 个人开源作品,即时通讯App支持文本、语音、图片聊天
开源一个即时通讯类App,支持纯文本.语音.地理位置.图片聊天,同时还加入了好友圈功能,支持分享动态和发送图片,支持搜索附近的人,使用的百度地图定位功能:由Bmob后端云提供服务器支持,欢迎喜欢的伙伴 ...
- IOS GCD 浅析
一.简单介绍 1.队列的类型: 1.1主队列:main queue 主线程队列,更新UI的操作.是一个串行的队列,串行队列每次只处理一个任务. 1.2系统创建的并发队列:glob ...
- Android Service使用拾遗[阿里工程师分享]
Service作为android的四大组件之一常用来帮助我们完成一些需要放在后台处理的任务,通过startService和bindService两种方式被调用.因为Service也是在主线程中运行的, ...
- mac os x使用Git简易入门教程
具体如下: 1, 首先要了解什么是Git. 简而言之,Git是一个分布式的代码版本管理工具.类似的常用工具还有SVN,CVS. 概念了解参见:http://baike.baidu.com/subvie ...
- iOS之UI--微博个人详情页
前言:微博个人详情页,和我常用的的QQ空间的详情页是同样的.要求能够融会贯通,做这一类的界面能够快速上手实现. 动态图效果展示: 直接使用UINavigationBar->UITableView ...
- [转]android访问网络:java.net.ConnectException: localhost/127.0.0.1:8888 - Connection refused
这对刚学会向tomcat模拟的本地服务器发送请求的同学非常重要! 转自:http://wing123.iteye.com/blog/1873763 描述:在做注册功能的时候,向本地服务器:127.0. ...
- swipe js dynamic content
swipe js dynamic content swipe 动态改变内容时,需要用 update 一下. swiper.update(true); 实例: HTML Code 页面用的FreeMa ...
- iOS 应用架构浅谈
当我们讨论客户端应用架构的时候,我们在讨论什么? 其实市面上大部分应用不外乎就是颠过来倒过去地做以下这些事情: 简单来说就是调API,展示页面,然后跳转到别的地方再调API,再展示页面. App确实就 ...
- 优秀的PHP开源项目集合
包管理Package Management Package Management Related 框架 框架组件 微框架Micro Frameworks 内容管理系统Content Managemen ...