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的更多相关文章

  1. Socket programming in C on Linux | tutorial

    TCP/IP socket programming This is a quick guide/tutorial to learning socket programming in C languag ...

  2. 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 ...

  3. [PHP-Socket] Socket Programming in PHP

    Simple Client-Server socket program in PHP Introduction Sockets are used for interprocess communicat ...

  4. Socket Programming in C#--Getting Started

    Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...

  5. Socket Programming in C#--Introduction

    This is the second part of the previous article about the socket programming. In the earlier article ...

  6. 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 ...

  7. linux c socket programming

    原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...

  8. TCP Socket Programming in Node.js

    TCP Socket Programming in Node.js Posted on October 26th, 2011 under Node.jsTags: Client, node.js, S ...

  9. 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 ...

随机推荐

  1. EL表达式概述

    E L(Expression Language) 目的:为了使JSP写起来更加简单.表达式语言的灵感来自于 ECMAScript 和 XPath 表达式语言,它提供了在 JSP 中简化表达式的方法. ...

  2. 手把手搭建自己的android环境

    最近想学习安卓,不过国内实在被墙的厉害,真是"万里安装只被墙".安装的过程中也出现了几个问题.所以记录下来,免得自己下次再次安装的时候又来重蹈覆辙. 以下的问题也是按照出现的顺序排 ...

  3. win7开启休眠功能

    win7有的系统默认关机选项没有休眠功能,其实是没打开. cmd-> powercfg -hibernate on   即可

  4. 如何延长windows评估版的方法

    在软件的开发测试,通常使用的是windows评估版本.但是有时候它的使用期限不满足你的需求.所以你可以用一下方法来延长评估版的时间. 延長使用期限 跟 Windows Server 2008 延長使用 ...

  5. .NET 创建Windows服务,及服务的安装卸载

    .NET服务创建过程 http://jingyan.baidu.com/article/fa4125acb71a8628ac709226.html 相关命令(要以管理员身份打开cmd) 安装服务 -& ...

  6. JS中的bind方法学习

    EcmaScript5给Function扩展了一个方法:bind 众所周知 在jQuery和prototype.js之类的框架里都有个bind jQuery里的用途是给元素绑定事件 $("# ...

  7. 【mysql】索引的优化

    写在前面的话 查询容易,优化不易,且写且珍惜 mysql结构 从MySQL逻辑架构来看,MySQL有三层架构,第一层连接,第二层查询解析.分析.优化.视图.缓存,第三层,存储引擎 MySQL有哪些索引 ...

  8. 软件测试作业1--描述Error

    记忆犹新的错误: 上个学期选修了可视化这门课程,最后大作业用d3实现,在使用d3读取csv数据的时候出现了以下Error: 我先是在代码中读取了某csv格式的数据,并且将其存入变量root中,然后对r ...

  9. Rotate Array

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  10. 孙鑫视频学习:VS2010中找不到【Tab order】菜单项

    在学习孙鑫视频中,修改Tab顺序时,找不到VC6.0中提到的[Layout]->[Tab order]菜单项,但VC2010中可以用Ctrl+D调出来Tab顺序,或者[格式]->[Tab键 ...