设为首页 加入收藏

TOP

C#中Socket服务端代码分享(二)
2014-11-24 14:34:32 来源: 作者: 【 】 浏览:2
Tags:Socket 服务 代码 分享
// Add the workerSocket reference to our ArrayList
m_workerSocketList.Add(workerSocket);

// Send a welcome message to client
string msg = "Welcome client " + m_clientCount + "\n";
SendMsgToClient(msg, m_clientCount);

// Update the list box showing the list of clients (thread safe call)
UpdateClientListControl();

// Let the worker Socket do the further processing for the
// just connected client
WaitForData(workerSocket, m_clientCount);

// Since the main Socket is now free, it can go back and wait for
// other clients who are attempting to connect
m_mainSocket.BeginAccept(new AsyncCallback ( OnClientConnect ),null);
// Wait until a connection is made before continuing.等待连接创建后继续
allDone.WaitOne();
}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been closed\n");
}
catch(SocketException se)
{
MessageBox.Show ( se.Message );
}

}




public class SocketPacket
{
// Constructor which takes a Socket and a client number
public SocketPacket(System.Net.Sockets.Socket socket, int clientNumber)
{
m_currentSocket = socket;
m_clientNumber = clientNumber;
}
public System.Net.Sockets.Socket m_currentSocket;
public int m_clientNumber;
// Buffer to store the data sent by the client
public byte[] dataBuffer = new byte[1024];
}
// Start waiting for data from the client
public void WaitForData(System.Net.Sockets.Socket soc, int clientNumber)
{
try
{
if ( pfnWorkerCallBack == null )
{
// Specify the call back function which is to be
// invoked when there is any write activity by the
// connected client
pfnWorkerCallBack = new AsyncCallback (OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket (soc, clientNumber);
//receiveDone.Reset();
soc.BeginReceive (theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length,
SocketFlags.None,
pfnWorkerCallBack,
theSocPkt);
//receiveDone.WaitOne();
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
// This the call back function which will be invoked when the socket
// detects any client writing of data on the stream
public void OnDataReceived(IAsyncResult asyn)
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState ;
try
{
// Complete the BeginReceive() asynchronous call by EndReceive() method
// which will return the number of characters written to the stream
// by the client
//receiveDone.Set();
int iRx = socketData.m_currentSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
// Extract the characters as a buffer

首页 上一页 1 2 3 4 下一页 尾页 2/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇AMF序列化为对象和AMF序列化为二.. 下一篇C#获取当前运行的源代码的文件名..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: