【求救SOS】C# EndRead IO异常,与 asyneccallback 异常
最近在写一个大厅游戏,可是写到客户端的时候,登录可以完成,但进入大厅的时候就会出异常(第二次请求)服务器没有响应,服务器console标记没有输出。调试发现在第二次请求时,asynccallback并没有调用回调,而是binarywriter输出后就结束了,有时还会出现线程被终止,我想可能时asynccallback超时了。
请高赐教。……在线等待中…………………………
代码(客户端):1.
public class ClientStreamClass
{
public delegate void OutByte(Byte [] byt); //返回字節數據委托
public event OutByte MyOut;
private TcpClient tcpclient;
private Byte[] rebyte;
private MyBytes mybytes;
public ClientStreamClass(TcpClient tcp) {
rebyte = new Byte[1024];
mybytes = new MyBytes();
tcpclient = tcp;
}
public void SetAndSendStream(BaseModel bml) {
AsyncCallback acb = new AsyncCallback(MyGetStream);
tcpclient.GetStream().BeginRead(rebyte, 0, 1024, acb, null);
Byte[] sendbytes = ConverStream.GetSerializationBytes(bml);
SendMessage(sendbytes);
}
private void MyGetStream(IAsyncResult ar) {
int streamleng;//判斷數據長度
Boolean state = true;//數據是否讀取完
streamleng = tcpclient.GetStream().EndRead(ar);
if (streamleng < 1)
{
DisponseTcp();
return;
}
mybytes.AddBytes(rebyte, streamleng);
rebyte = new Byte[1024];
if (tcpclient.GetStream().DataAvailable) {
state = false;
tcpclient.GetStream().BeginRead
(rebyte, 0, 1024, new AsyncCallback(MyGetStream),tcpclient.GetStream());
}
if (state) {//数据读取完毕
MyOut(mybytes.ReceiveAllByte);//觸發事件
mybytes.Dispose();
}
}
//發送數據
private void SendMessage(Byte [] sendByte) {
BinaryWriter bw = new BinaryWriter(tcpclient.GetStream());
bw.Write(sendByte);
bw.Flush();
}
//銷毀連接
private void DisponseTcp()
{
if (tcpclient != null)
{
tcpclient.Close();
tcpclient = null;
}
}
}
form 窗体的调用如下:
2. try
{
ThreadReadStream();
}
catch (Exception ex) {
ErrorModel em = new ErrorModel();
em.Errorid = "501";
em.EventTime = DateTime.Now.ToString("YYYY-MM-DD hh:mm:ss");
em.Comeform = "client";
em.EMessage = ex.Message;
cpc.SendSystemInfo(cpc.ErrorExit(em));
if (tcpclient != null) {
tcpclient.Close();
tcpclient = null;
}
Application.Exit();
}
//调用 类1 .
private void ThreadReadStream() {
ClientStreamClass csc = new ClientStreamClass(tcpclient);
csc.MyOut += new ClientStreamClass.OutByte(this.StreamProtocolUse);
csc.SetAndSendStream(cpc.Get501Protocol() as BaseModel);
}