c#tcp server:从客户端收到不完整的结果

时间:2017-09-03 12:20:37

标签: c# tcp tcpclient tcpserver

问题:我在客户端使用DriveInfo.GetDrives()获取LogicalDrivesList,然后将结果发送回服务器,但服务器只显示第一个。如何才能在服务器中获得所有结果而不仅仅是第一个?

此代码将执行此操作:如果服务器键入“Drive”客户端将获取驱动器列表并发送回服务器,则服务器将发送下一个命令。但是服务器只显示“c:\”(并非所有结果都像“c:\” “d:\” “ e:\“和......)

服务器:

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
     // RECEIVE
     var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
     Console.WriteLine("Received: {0}", data);

     // SEND
     var command = Console.ReadLine();
     var commandToBytes = System.Text.Encoding.ASCII.GetBytes(command);
     stream.Write(commandToBytes, 0, commandToBytes.Length);
     Console.WriteLine("Sent: {0}", command);
}

客户端:

// Get a stream object for reading and writing
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    // RECEIVE
    var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
    switch (data)
    {
         case "Drive":
             var drives = DriveInfo.GetDrives();
             foreach (var drive in drives)
             {
                  // SEND
                  var commandToBytes = System.Text.Encoding.ASCII.GetBytes(Convert.ToString(drive));
                  stream.Write(commandToBytes, 0, commandToBytes.Length);
                  Console.WriteLine("Sent: {0}", drive);
             }
             return;
         default:
             return;
    }
}

在客户var drives = DriveInfo.GetDrives();中,类型为 DriveInfo []

var commandToBytes = System.Text.Encoding.ASCII.GetBytes(Convert.ToString(drive));类型为 字节[]

在服务器var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);中,类型为 字符串

0 个答案:

没有答案