// This is the call back function, which will be invoked when a client is connected
public void OnClientConnect(IAsyncResult asyn)
{
try
{
//让它继续处理并建立与客户端的连接
allDone.Set();
// Here we complete/end the BeginAccept() asynchronous call
// by calling EndAccept() - which returns the reference to
// a new Socket object
Socket workerSocket = m_mainSocket.EndAccept (asyn);
// Now increment the client count for this client
// in a thread safe manner
Interlocked.Increment(ref m_clientCount);
if (m_clientCount == 1)
{
lock (this)
{
stopwatch.Start();
dtStart = DateTime.Now;
writeLog("Server Start Socket Connect Time"+dtStart.ToString("yyyy-MM-dd HH:mm:ss fff"));
}
}
// 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 );
}
}
C#中Socket服务端代码分享(2)
内容版权声明:除非注明,否则皆为本站原创文章。