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. 一个基于Myeclipse开发的Java打地鼠小游戏(Appletcation)

    package javaes.zixue.wangshang.daima; 2 3 import java.awt.Cursor; import java.awt.Image; import java ...

  2. JAVA----编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符

    package com.pb.demo.packclass.demo1; import java.util.HashSet; /** * 编程列出一个字符串的全字符组合情况,原始字符串中没有重复字符 ...

  3. iOS 开发笔记

    1,Search Bar 怎样去掉背景的颜色(storyboard里只能设置background颜色,可是发现clear Color无法使用) 2,NSDate使用 3,UTTabviewCell 未 ...

  4. ReSharper 8.XXX 注册机

    今天给电脑重装系统,发现Rsharper已经更新到8.0.14.856了,于是下载新版本的,但像咱搞开发的,肯定不能用付费软件(关键是你也付不起啊,499$,499刀啊).于是在网上找相关的激活软件. ...

  5. 在Asp.net MVC中使用Authorization Manager (AzMan)进行Windows用户身份认证

    背景 创建需要通过Windows用户进行身份认证的Asp.net MVC应用 要点 在Asp.net MVC应用基于Windows用户进行身份认证的方法有很多,如MVC自带的Windows认证就经常被 ...

  6. 手动将自定制的WebPart部署到 SharePoint 2010 中

    1.搭建好开发环境,建立webpart工程,写代码. 2.修改assembly.cs文件   在部署前,需要修改assembly文件,增加以下两句: using System.Security; [a ...

  7. .net WEB程序访问locahost和IP使用

    1.服务都在本机调用用 localost 2.部署站点访问时用ip

  8. Struts2-tomcat报错:There is no Action mapped for namespace / and action

    HTTP Status 404 - There is no Action mapped for namespace / and action name first. type Status repor ...

  9. JSON 格式介绍

    转自:http://www.json.org/json-zh.html JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机器 ...

  10. 使用dbms_logmnr查看日志文件

    大多为了寻找被意外修改的数据或者那条sql修改了哪些数据 如果是在线重做日志的话需要该日志是inactive模式下的 查询v$log和v$logfile获取相关信息 执行exec dbms_logmn ...