繁体   English   中英

C#TCP套接字服务器客户端连接

[英]C# tcp socket server client connection

真的需要你的帮助。

我的项目是通过电缆连接两台PC,并使用tcp套接字将客户端文本框形式的字符串发送到服务器。 问题是我只能发送一个字符串,然后连接会关闭。

客户端代码(c#):当然是使用try catch方法:

       String str = textBox2.Text;
       Stream stm = tcpclnt.GetStream();

        ASCIIEncoding asen = new ASCIIEncoding();
    byte[] ba = asen.GetBytes(str);
 textBox1.Text="Sending...";

 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();

 //////////////

服务器代码:也可以使用try catch方法:

   int k = 0;
   byte[] b = new byte[100];
   for (; ; )
   {
       for (int i = 0; i < 100000; i++)
       { }
           k = s.Receive(b);
       MessageBox.Show(k + "");
       textBox1.Text = "Recieved...";

       for (int i = 0; i < k; i++)
       {
           textBox2.Text = textBox2.Text + Convert.ToChar(b[i]);
       }
       MessageBox.Show(k + "");
       ASCIIEncoding asen = new ASCIIEncoding();
       s.Send(asen.GetBytes("Automatic message:" + "String received by server!"));
       textBox1.Text = "\n Automatic message sent!";


       MessageBox.Show(k + "");
     s.Close();
       }

我的问题是:我可以在服务器中循环发送多个字符串,而无需关闭连接吗?

注意:按下每种形式的按钮后,将分别执行客户端和服务器。

注意:将在某些端口上建立连接并成功加载表格。

首先,将关闭项移出for循环

   int k = 0;
   byte[] b = new byte[100];
   for (; ; )
   {
       for (int i = 0; i < 100000; i++)
       { }
       k = s.Receive(b);
       MessageBox.Show(k + "");
       textBox1.Text = "Recieved...";

       for (int i = 0; i < k; i++)
       {
           textBox2.Text = textBox2.Text + Convert.ToChar(b[i]);
       }
       MessageBox.Show(k + "");
       ASCIIEncoding asen = new ASCIIEncoding();
       s.Send(asen.GetBytes("Automatic message:" + "String received by server!"));
       textBox1.Text = "\n Automatic message sent!";


       MessageBox.Show(k + "");
     }
     s.Close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM