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. C语言中do...while(0)用法小结

    在linux内核代码中,经常看到do...while(0)的宏,do...while(0)有很多作用,下面举出几个: 本文地址:http://www.cnblogs.com/archimedes/p/ ...

  2. Android Plugin

    工欲善其事,必先利其器.以下介绍一些常用的Android Plugin,有助于开发. 1.adb-idea 支持在AS面板中,执行ADB命令.不过如果用惯命令行的话,可以不安装: 2.android- ...

  3. android:descendantFocusability=”blocksDescendants”的用法

    android:descendantFocusability用法简析 开发中很常见的一个问题,项目中的listview不仅仅是简单的文字,常常需要自己定义listview,自己的Adapter去继承B ...

  4. Retrofit源码设计模式解析(上)

    Retrofit通过注解的方法标记HTTP请求参数,支持常用HTTP方法,统一返回值解析,支持异步/同步的请求方式,将HTTP请求对象化,参数化.真正执行网络访问的是Okhttp,Okhttp支持HT ...

  5. IOS开发--常用工具类收集整理(Objective-C)(持续更新)

    前言:整理和收集了IOS项目开发常用的工具类,最后也给出了源码下载链接. 这些可复用的工具,一定会给你实际项目开发工作锦上添花,会给你带来大大的工作效率. 重复造轮子的事情,除却自我多练习编码之外,就 ...

  6. 第一次开发PHP网页Hello PHP

    打开安装好的XAMPP的三个服务: 然后打开phpStorm,在Open选项选择文件目录(最后一个目录是htdocs)打开: 3.有时候可能无法修改php文件,会弹出一些提示窗口.那么就打开Finde ...

  7. 使用JUnit4进行java单元测试

     第一步:创建一个java工程,在工程中创建一个被单元测试的Student数据类,代码如下: package com.junittest.yu; public class Student { priv ...

  8. nginx location匹配规则

    谢谢作者的分享精神,原文地址:http://www.nginx.cn/115.html location匹配命令 ~      #波浪线表示执行一个正则匹配,区分大小写~*    #表示执行一个正则匹 ...

  9. CSS从大图片上截取小图标的操作(转)

    一张图片,用CSS分割成多个小图标. css样式: .icon{ background:url(../images/tabicons.png) no-repeat;width:18px; line-h ...

  10. HTML实体对照表

    HTML开发特殊字符是没办法原样输出的,必须用到实体,为了以后查看方便,收藏一下实体对照表是必要的,另外,使用<xmp></xmp>标签可以原样输出,当然,也包括特殊字符啦! ...