无法通过TCP / IP发送第二条消息

时间:2016-05-31 12:18:09

标签: c# tcpclient tcplistener

我正在尝试使用TCPClientTCPListner类在c#应用程序中通过TCP / IP发送消息

以下是我从codeproject网站获得的代码。

客户 code written over btn click

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

            tcpclnt.Connect("192.168.0.102", 8001);
            // use the ipaddress as in the server program

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

            String str = textBox1.Text;
            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 ex)
        {
            Console.WriteLine("Error..... " + ex.Message);
        }

服务器 code written on form_load

try
        {
            IPAddress ipAd = IPAddress.Parse("192.168.0.102");
            // use local m/c IP address, and 
            // use the same in the client

            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, 8001);

            /* Start Listeneting at the specified port */
            myList.Start();

            Console.WriteLine("The server is running at port 8001...");
            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");

            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);
            Console.WriteLine("Recieved...");
            string str = string.Empty;
            for (int i = 0; i < k; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                str = str + Convert.ToChar(b[i]);

            }
            label1.Text = str;
            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            /* clean up */
            s.Close();
           // myList.Stop();

        }

client上,我在tcp上发送了一个用文本框写的字符串,并且server收到了很好的信息。

但是当我尝试发送另一个字符串时,它会在没有任何exception的情况下失败,并且客户端应用程序会挂起无限时间。

这里有什么问题?

2 个答案:

答案 0 :(得分:1)

查看您提供的代码,服务器只会尝试从客户端读取1条消息,因此需要将其放入循环中以从客户端读取多条传入消息,处理消息并发送响应然后获取更多消息消息。

另请注意,服务器当前只需要一个客户端连接,处理该客户端然后关闭。

客户端在示例中的设置基本相同,因此您无法修改其中的工作方式而不会修改另一个。

答案 1 :(得分:1)

服务器应始终处于侦听模式,即服务器代码应处于while循环中,以便它可以连续接受客户端。您的服务器将接受一个客户端,然后关闭自己。因此,如果单击客户端按钮,新客户端将尝试连接到服务器,但现在服务器无法使用。

相关问题