Re: [問題] 請教一個 TcpListener 問題

看板C_Sharp (C#)作者 (每天都肚子餓)時間18年前 (2007/05/31 09:25), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/4 (看更多)
※ 引述《cole945 (躂躂..)》之銘言: : 因為原本的socket和NetworkStream本來就已經是non-buffered.. : 所以應該不會有等待的問題.. : 問題可能是, 你除了用NetworkStream, 又另外使用其他的IOStream : 來把資料導到 NetworkStream, 但這個 IOStream 是buffered, : 那就有可能發生這個問題.. : 如果是這樣的話, 就呼叫該 IOStream的 Flush() 來強制處裡IO.. : 這種問題通常是發生在Write而不是Read.. : 如果不是這樣的話, 來點code看看吧^^? 先謝謝前輩的指導 ^^ 因為原程式 code 有點長, 我把 non-blocking 改成 blocking 並簡化成下面 (結果是一樣的) /////////////////////////////////////////////////////////////////// Server Side: listener = new TcpListener(port); listener.Server.NoDelay = true; listener.Start(); client = listener.AcceptTcpClient(); stream = client.GetStream(); try { while(true) { if (stream.CanRead) { byte[] bytes = new byte[client.ReceiveBufferSize]; int dataLen = stream.Read(bytes, 0, (int)client.ReceiveBufferSize); if (dataLen >= 1) Console.WriteLine("{0}\n---", Encoding.Default.GetString(bytes, 0 \ , dataLen)); } else ................... } } catch (Exception e) { ........... } /////////////////////////////////////////////////////////////////// Client Side: try { ipendpoint = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()). \ AddressList[0], 0); tcpclient = new TcpClient(ipendpoint); remoteEP = new IPEndPoint(IPAddress.Parse(REMOTE_IP), REMOTE_PORT); tcpclient.NoDelay = true; tcpclient.Connect(remoteEP); netstream = tcpclient.GetStream(); // while(true) { if (netstream.CanWrite) { Byte[] sendBytes = Encoding.UTF8.GetBytes("aaa"); netstream.Write(sendBytes, 0, sendBytes.Length); netstream.Flush(); sendBytes = Encoding.UTF8.GetBytes("bbb"); netstream.Write(sendBytes, 0, sendBytes.Length); netstream.Flush(); Thread.Sleep(3000); sendBytes = Encoding.UTF8.GetBytes("ccc"); netstream.Write(sendBytes, 0, sendBytes.Length); netstream.Flush(); } } } catch (Exception e) { ............... } /////////////////////////////////////////////////////////////////// 我用 VC6 寫個小程式在中間做驗證 VC6 -- Client 這邊,會正常顯示 : aaa --- bbb --- ccc --- 接著,不管是 VC6 往 Server 丟資料,或是 Client 往 Server 丟資料 Server 收到: aaabbb --- ccc --- 所以才會有此疑惑 :S -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 116.59.115.8
文章代碼(AID): #16NYGbU5 (C_Sharp)
文章代碼(AID): #16NYGbU5 (C_Sharp)