当写成两遍或以上的Write()给服务端接收有可能只能接收到一条信息,即下面的“客户端数据提交1/n”,应在服务端的接收段和客户端接收段编写相应延时代码,以达到数据完全接收。
Server Code:
while (!done)
{
TcpListener listener = new TcpListener(8000);
listener.Start();
byte[] bytes = new byte[1024];
int bytesRead = 0;
TcpClient client = new TcpClient();
NetworkStream ns = null;
Console.Write("正在侦听端口...");
client = listener.AcceptTcpClient();
Console.WriteLine("/n处理连接请求...");
ns = client.GetStream();
bytes = new byte[1024];
//延时获取全部数据
Delay(0.1);//
bytesRead = ns.Read(bytes, 0, bytes.Length);
Console.WriteLine(Encoding.BigEndianUnicode.GetString(bytes,0,bytesRead));
.....
}
Client Code:
TcpClient client=new TcpClient("192.168.8.88",8000);
NetworkStream ns=client.GetStream();
byte[] byteTime=Encoding.BigEndianUnicode.GetBytes("客户端数据提交1/n");
ns.Write(byteTime,0,byteTime.Length);
ns.WriteTimeout = 10;
byte[] clientIp = Encoding.BigEndianUnicode.GetBytes("客户端数据提交2/n客户端IP地址:" + Request.UserHostAddress + "/n");
ns.Write(clientIp,0,clientIp.Length);
//
byte[] Test = Encoding.BigEndianUnicode.GetBytes("testing/n");
ns.Write(Test, 0, Test.Length);
byte[] bytes=new byte[1024];
ns.ReadTimeout = 10;
Delay(0.1);
int bytesRead=ns.Read(bytes,0,bytes.Length);
showLabel.Text = "服务器返回信息:" + Encoding.BigEndianUnicode.GetString(bytes);
............
延时过程:
private static void Delay(double second)
{
DateTime now = DateTime.Now;
while (now.AddSeconds(second) > DateTime.Now)
{
}
}