Socket Programming in C#--Multiple Sockets
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的更多相关文章
- Socket programming in C on Linux | tutorial
TCP/IP socket programming This is a quick guide/tutorial to learning socket programming in C languag ...
- 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 ...
- [PHP-Socket] Socket Programming in PHP
Simple Client-Server socket program in PHP Introduction Sockets are used for interprocess communicat ...
- Socket Programming in C#--Getting Started
Getting Started You can argue that one can overcome these shortcomings by multithreading meaning tha ...
- Socket Programming in C#--Introduction
This is the second part of the previous article about the socket programming. In the earlier article ...
- 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 ...
- linux c socket programming
原文:linux c socket programming http://54min.com/post/http-client-examples-using-c.html 好文章 PPT http:/ ...
- TCP Socket Programming in Node.js
TCP Socket Programming in Node.js Posted on October 26th, 2011 under Node.jsTags: Client, node.js, S ...
- 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 ...
随机推荐
- Android studio打包APK混淆配置
要在打包APK时加入混淆需要在Module中的buid.gradle中加入如下信息 buildTypes { release { minifyEnabled true shrinkResources ...
- IOS组件绑定无效错误
报错的原因:界面按钮事件没有绑定到源代码或者相关的代码被注释了.比如你的button组件以及绑定到IBOutlet,但是viewcontrol.m上没有相关的代码,就会出现异常.
- Effective Java 19 Use interfaces only to define types
Reason The constant interface pattern is a poor use of interfaces. That a class uses some constants ...
- 处理 InterruptedException——Brian Goetz
本文转自Brian Goetz大师在IBM的developerWorks中发布的文章: 中文地址:http://www.ibm.com/developerworks/cn/java/j-jtp0523 ...
- 解读Python发送邮件
解读Python发送邮件 Python发送邮件需要smtplib和email两个模块.也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单.今天,就来好好学习一下使用Pyt ...
- NoSQL介绍
NoSQL(Not Only SQL),是一种非关系型数据库:说到这里,大家需要了解关系型数据库和非关系型数据库的区别,可参考:从关系型数据库到非关系型数据库. NoSQL是以key-value形式存 ...
- 第二章 Mysql 数据类型简介--(整数类型、浮点数类型和定点数类型,日期与时间类型,字符串类型,二进制类型)
第一节:整数类型.浮点数类型和定点数类型 1,整数类型 2,浮点数类型和定点数类型 M 表示:数据的总长度(不包括小数点):D 表示:小数位:例如 decimal(5,2) 123.45存入数据的时候 ...
- cordova Process finished with exit code -1
安装完cordova之后,创建一个测试项目后,运行报Process finished with exit code -1,经过查找原因,是因为gradle没有安装,在http://www.androi ...
- lvs realserver 配置VIP
# $# 表示提供到shell脚本或者函数的参数总数: # 1表示只有一个参数. #/bin/bash #file: tun_RS.sh if [ $# -ne 1 ]; then echo “usa ...
- shell exit 0 exit 1
其实都一样,都是退出,只不过返回这个0和1是返回给操作系统的错误或者正确代码. exit 1 指的是脚本运行的返回值,用来指示成功或失败,以及失败的原因. exit 0 表示成功,exit 1表示失败 ...