使用未通过基本tcp接口接收的NetworkStream数据时

时间:2015-02-01 19:33:48

标签: c# tcp tcp-ip

我正在创建一个基本的TicTacToe程序,以便在互联网上与我的朋友对战(这是为了学习网络编程的基础知识)。问题是虽然客户端收到了正确的数据,但是当它尝试发送数据时,即使代码正确执行,也不会发送任何数据。

以下是客户端软件:

string input;
Board board = new Board();
while (true)
{
    TcpClient tcpclnt = new TcpClient();
    tcpclnt.Connect("192.168.0.10", 5000);

    byte[] b = new byte[1024];

    NetworkStream ns = tcpclnt.GetStream();

    int k = ns.Read(b, 0, 100);//recieve data from host
    string sRecieve = string.Empty;

    for (int i = 0; i < k; i++)
        sRecieve += Convert.ToChar(b[i]);

    Console.WriteLine(sRecieve);

    input = Console.ReadLine();

    ASCIIEncoding asen = new ASCIIEncoding();
    byte[] ba = asen.GetBytes(input);

    ns.Write(ba, 0, ba.Length);
    tcpclnt.Close();
}

这是服务器代码(这是连接发生时的所有内容):

    TcpListener tcpList = new TcpListener(IPAddress.Any, 5000);
    tcpList.Start();

    Console.WriteLine("Waiting for valid connection");
    Socket s = tcpList.AcceptSocket();
    Console.WriteLine("Connection accepted from: " + s.RemoteEndPoint);

    ASCIIEncoding asen = new ASCIIEncoding();
    s.Send(asen.GetBytes(board.ToString()));//send data
    Console.WriteLine("sent board layout");

    byte[] b = new byte[1024];

    Console.WriteLine("Waiting for next play");
    int k = s.Receive(b);
    Console.WriteLine("Received next play");

    string sInput = string.Empty;

    for (int i = 0; i < k; i++)
        input += Convert.ToChar(b[i]);

0 个答案:

没有答案