首页 文章

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

提问于
浏览
0

真的需要你的帮助 .

我的项目是通过电缆连接两台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();
       }

我的问题是:我可以在服务器中创建一个不仅仅发送一个字符串的循环,我需要发送许多字符串而不关闭连接 .

注意:按下每个表单中的按钮后,每个客户端和服务器都会被执行 .

注意:某些端口上的连接将 Build 并在表单加载中成功 .

1 回答

  • 0

    首先,将关闭移出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();
    

相关问题