110,539
社区成员
发帖
与我相关
我的任务
分享
Thread th= new Thread(new ThreadStart(InitialPPTTcp));
th.IsBackground = true;
th.Start();
public void InitialPPTTcp()
{
TcpListener pptListener = new TcpListener(ip,8506);
pptListener.Start();
TcpClient pptClient = pptListener.AcceptTcpClient();
pptBeginRead(pptClient);
}
private void pptBeginRead(TcpClient pptClient)
{
this.pptClient = pptClient;
pptRemoteEndPoint = pptClient.Client.RemoteEndPoint.ToString();
pptStreamToClient = pptClient.GetStream();
pptBuffer = new byte[pptBufferSize];
pptHandler = new ProtocolHandler();
AsyncCallback pptCallBack = new AsyncCallback(pptOnReadComplete);
pptStreamToClient.BeginRead(pptBuffer, 0, pptBufferSize, pptCallBack, are.WaitOne());
}
private void pptOnReadComplete(IAsyncResult ar)
{
int bytesRead = 0;
try
{
lock (pptStreamToClient)
bytesRead = pptStreamToClient.EndRead(ar); //这里出错了。
string msg = Encoding.Unicode.GetString(buffer, 0, bytesRead);
Array.Clear(pptBuffer, 0, pptBuffer.Length); //清空缓存,避免脏读。
string[] protocolArray = pptHandler.GetProtocol(msg);
foreach (string pro in protocolArray)
{
ParameterizedThreadStart start = new ParameterizedThreadStart(pptHandleProtocol);
start.BeginInvoke(pro, null, null);
}
//无限循环
lock (pptStreamToClient)
{
AsyncCallback callBack = new AsyncCallback(pptOnReadComplete);
pptStreamToClient.BeginRead(pptBuffer, 0, pptBufferSize, callBack, null);
}
}
catch (Exception ex)
{
if (pptStreamToClient != null)
pptStreamToClient.Dispose();
pptClient.Close();
frmMessageBoxDialog.Show(ex.StackTrace, "错误", MessageBoxButtonEx.OK, MessageBoxIconEx.Error);
return;
//MessageBox.Show(ex.Message);
}
}