作者kekul (每天都肚子饿)
看板C_Sharp
标题Re: [问题] 请教一个 TcpListener 问题
时间Thu May 31 09:25:56 2007
※ 引述《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