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. IOS 开发一些常用的地址

    1.开发者中心 https://developer.apple.com/membercenter/index.action 2.itunesconnect https://itunesconnect. ...

  2. String.format() 格式化字符串

    1.几种常见的转换符 转换符 说明 实例 %d 整数类型(十进制) 99 %f 浮点类型 99.99 %s 字符串类型 "mingrisoft" %c 字符类型 'm' %b 布尔 ...

  3. java多线程系列1--线程实现与调度

    java的重要功能之一就是内部支持多线程,这一系列文章将详细剖析java多线程的基础知识 多线程概述 多线程引入 程序只有一个执行流程,所以这样的程序就是单线程程序. 假如一个程序有多条执行流程,那么 ...

  4. swift基础二

    import Foundation // MARK: - ?和!的区别 // ?代表可选类型,实质上是枚举类型,里面有None和Some两种类型,其实nil相当于OPtional.None,如果非ni ...

  5. IOS 自定义按钮(代码实现)+九宫格

    在一些下载应用里整个页面都是按钮,有好多好多,但是仔细观察不难发现他们很有规律.就像下面一样

  6. 多线程在iOS开发中的应用

    多线程基本概念 01 进程 进程是指在系统中正在运行的一个应用程序.每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内. 02 线程 2-1 基本概念 1个进程要想执行任务,必须得有线程 ...

  7. Java眼中的XML--文件读取--1 应用DOM方式解析XML

    初次邂逅XML: 需要解析的XML文件: 这里有两个book子节点. 1.如何进行XML文件解析前的准备工作,另外解析先获取book节点. 这个我后来看懂了: 这个Node的ELEMENT_NODE= ...

  8. 大家一起和snailren学java-(二)一切都是对象

    “今天是周末,虽然外面阳光晴好,但是作为一名单身狗,还是除了寝室,就只有图书馆了.Anyway,既然没有对象,那我们就在java中找对象吧,哈哈.没有对象的人,看一切,都是对象!” 在面向对象程序设计 ...

  9. Effective Java 41 Use overloading judiciously

    The choice of which overloading to invoke is made at compile time. // Broken! - What does this progr ...

  10. 被废弃的 Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit

    最近学习多线程的知识,看到API里说这些方法被废弃了,就查了一下原因 Thread.stop 这个方法会解除被加锁的对象的锁,因而可能造成这些对象处于不一致的状态,而且这个方法造成的ThreadDea ...