设为首页 加入收藏

TOP

C#中Socket服务端代码分享(四)
2014-11-24 14:34:32 来源: 作者: 【 】 浏览:4
Tags:Socket 服务 代码 分享
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer,
0, iRx, chars, 0);

System.String szData = new System.String(chars);
string msg = "" + socketData.m_clientNumber + ":";
AppendToRichEditControl(msg + szData);
//writeFromClientsMsgLog(msg + szData);

// Send back the reply to the client
string replyMsg = "Server Reply:" + szData.ToUpper();
// Convert the reply to byte array
byte[] byData = System.Text.Encoding.ASCII.GetBytes(replyMsg);

Socket workerSocket = (Socket)socketData.m_currentSocket;
workerSocket.Send(byData);


if (m_clientCount == iConnectNum && Flage == 0)
{
Interlocked.Increment(ref Flage);
string msgTime = "Server End Socket Action Time:";
lock(this)
{
stopwatch.Stop();
//lblTime.Text = stopwatch.Elapsed.Seconds.ToString();
int itime = stopwatch.Elapsed.Milliseconds;

//msgTime += stopwatch.Elapsed.Seconds.ToString()+"--"+itime.ToString();
msgTime += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff");
}
writeLog(msgTime);

writeClientConnectionLog();

//UpdateLabelTime(msgTime);
//byData = System.Text.Encoding.ASCII.GetBytes(msgTime);
//workerSocket.Send(byData);
}

// Continue the waiting for data on the Socket
WaitForData(socketData.m_currentSocket, socketData.m_clientNumber );

}
catch (ObjectDisposedException )
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch(SocketException se)
{
if(se.ErrorCode == 10054) // Error code for Connection reset by peer
{
string msg = "Client " + socketData.m_clientNumber + " Disconnected" + "\n";
AppendToRichEditControl(msg);
//writeFromClientsMsgLog(msg);

// Remove the reference to the worker socket of the closed client
// so that this object will get garbage collected
m_workerSocketList[socketData.m_clientNumber - 1] = null;
UpdateClientListControl();
}
else
{
MessageBox.Show (se.Message );
}
}
}




void CloseSockets()
{
if(m_mainSocket != null)
{
m_mainSocket.Close();
}
Socket workerSocket = null;
for(int i = 0; i < m_workerSocketList.Count; i++)
{
workerSocket = (Socket)m_workerSocketList[i];
if(workerSocket != null)
{
workerSocket.Close();
workerSocket = null;
}
}
}


void SendMsgToClient(string msg, int clientNumber)
{
// Convert the reply to by

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

评论

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