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. batch_size 和 fetch_size作用

    hibernate抓取策略,,batch-szie在<class>上的应用 batch-size属性,可以批量加载实体类, hbm.xml classes.hbm.xml <?xml ...

  2. 演示 pull解析的基本步骤(代码演示)

       pull解析器:            * 反序列化:将xml中的数据取出                1.导入jar包                2.创建解析器工厂           ...

  3. 一些在IOS中关于JS、H5开发的网站

    1.JSPatch 2.

  4. Resharper注册机实现以及源代码

    一直用Resharper,每次找注册机也麻烦,就想怎么才能自己能做个注册机,把它原理给搞懂了,不就不用找了.今天早上起来研究了下Resharper注册机,网上找到一位大神之前做Resharper注册机 ...

  5. 关于ajax请求数据后,数据本身的js失效的一些想法

    今天遇到一个头疼的问题.我做一个左右翻页效果(客户要求能够无限翻页),所以只能动态请求数据,进行局部刷新操作. 这时候问题就出来了,当我请求翻页的时候,数据通过js填充到div里面,但这些数据,自身带 ...

  6. SQL 在表中随机取数据

    在一张10万行产品表(Product)中,随机取10条数据的几种方式: SET STATISTICS IO ON SELECT TOP 10 ID FROM dbo.Product(NOLOCK) W ...

  7. python 连接 mysql

    http://blog.csdn.net/yelbosh/article/details/7498641 数据库的连接 模块引入之后我们就需要和数据库进行连接了,实例代码如下: db = MySQLd ...

  8. 搭建Struts2不同版本jar包不同

    struts2的版本比较多,所以在开发的时候特别要注意版本不同所需引入的包是不一样的.否则,会出现各种问题.而且很难找到问题所在. 以下是我遇到的问题总结: 一.当我运用struts2.3.4.1时, ...

  9. Bootstrap 类解析

    Bootstrap 类解析 元素 Bootstrap 类 定义 <div> container 内容容器 <table> table 表格 <table> tabl ...

  10. PL/SQL之--函数

    一.函数 函数是作为数据库对象存储在oracle数据库中,函数又被称为PL/SQL子程序.oracle处理使用系统提供的函数之外,用户还可以自己定义函数.函数通常被作为一个表达式来调用或存储过程的一个 ...