【发布时间】:2013-11-20 05:43:53
【问题描述】:
真的需要你的帮助。
我的项目是通过电缆连接两台 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();
}
我的问题是:我可以在服务器中创建一个循环来发送不仅仅是一个字符串,我需要在不关闭连接的情况下发送许多字符串。?
注意:客户端和服务端每一个都会在每个表单中的按钮按下后执行。
注意:某些端口上的连接将在表单加载中建立并成功。
【问题讨论】:
-
是的,您可以创建一个循环并发送任意数量的内容。在完成之前,您无需关闭套接字。
-
我不知道怎么做,我在服务器中做了一个循环,但是 k=s.recieve(b) 会卡住它。