C#Server Client似乎只能以一种方式工作

时间:2017-01-23 23:18:27

标签: c# sockets server client

我正在尝试在C#中的客户端和服务器之间发送数据。我对此很新。我在同一台机器上运行这些,因此是localhost。

服务器可以从客户端接收数据,但即使发送了客户端,客户端也似乎永远不会收到回复。

客户端: 客户端将数据(“apple”)发送到服务器并应收到回复。

       TcpClient client = new TcpClient("localhost", 1334); //Currently localhost
        StreamReader sr = new StreamReader(client.GetStream());
        StreamWriter sw = new StreamWriter(client.GetStream());

        string sendData = "apple";
        sw.WriteLine(sendData);
        sw.Flush();

        string data = sr.ReadLine();

        if (data != null)
        {
         MessageBox.Show("It worked!");
         }
         else
         {
           MessageBox.Show("No data.");
         }


        client.Close();

服务器 服务器将侦听数据。当它收到数据时,它会检查它是否是苹果,然后回答“是”。

        TcpListener listener = new TcpListener(1334);
        listener.Start();

        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            StreamReader sr = new StreamReader(client.GetStream());
            StreamWriter sw = new StreamWriter(client.GetStream());

            string request = sr.ReadLine();

            if(request == "apple")
            {
                Console.WriteLine(request); // Print that to the console so we know it was received okay
                sw.WriteLine("yes\n");
                client.Close();
            }

感谢所有帮助。

1 个答案:

答案 0 :(得分:0)

Furmek评论道:

  

我看到两件事:添加一个sw.Flush();在服务器端之前   client.Close();

工作服务器代码

    TcpListener listener = new TcpListener(1334);
    listener.Start();

    while (true)
    {
        TcpClient client = listener.AcceptTcpClient();
        StreamReader sr = new StreamReader(client.GetStream());
        StreamWriter sw = new StreamWriter(client.GetStream());

        string request = sr.ReadLine();

        if(request == "apple")
        {
            Console.WriteLine(request); // Print that to the console so we know it was received okay
            sw.WriteLine("yes\n");
            sw.Flush(); // sw.Flush(); Added here!!
            client.Close();
        }