2

这个问题可能会被问很多次..但我正在处理的场景有点差异,但非常简单..我正在克服错误并且到目前为止没有得到任何解决方案..这是我的客户端代码,我在其中遇到错误“阅读”以粗体突出显示..请提前帮助..thnx。

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net.Security;
using System.Timers;

namespace ClientRequest
{
class Program
{
    static void Main(string[] args)
    {
        try
        {

            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");

            IPAddress[] objLocalAddr = null;
            String strHostName = "";
            int port = 2425;

            strHostName = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            objLocalAddr = ipEntry.AddressList;

            tcpclnt.Connect(objLocalAddr[0], port);


            Console.WriteLine("Connected");
            Console.Write("Enter the string to be transmitted : ");

            String str = Console.ReadLine();
            Stream stm = tcpclnt.GetStream();

            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] ba = asen.GetBytes(str);
            Console.WriteLine("Transmitting.....");

            stm.Write(ba, 0, ba.Length);

            byte[] bb = new byte[100];
            **int k = stm.Read(bb, 0, 100);**                
            for (int i = 0; i < k; i++)
            Console.Write(Convert.ToChar(bb[i]));               

               tcpclnt.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
         }
      }
  }
}
4

1 回答 1

0

在执行读取功能之前,请执行以下操作:

if( stm.CanRead && stm.DataAvailable )
{
    int k = stm.Read(bb, 0, 100);
    for (int i = 0; i < k; i++)
        Console.Write(Convert.ToChar(bb[i]));               
}

tcpclnt.Close();
于 2012-10-16T12:53:58.423 回答