C# 无法通过TCP/IP发送第二条消息
我试图使用C# 无法通过TCP/IP发送第二条消息,c#,tcpclient,tcplistener,C#,Tcpclient,Tcplistener,我试图使用TCPClient和TCPListner类在c#应用程序中通过TCP/IP发送消息 以下是我从codeproject网站获得的代码 客户端通过btn写入的代码点击 try { TcpClient tcpclnt = new TcpClient(); Console.WriteLine("Connecting....."); tcpclnt.Connect("192.168.0.102", 8001
TCPClient
和TCPListner
类在c#应用程序中通过TCP/IP发送消息
以下是我从codeproject网站获得的代码
客户端通过btn写入的代码点击
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);
}
在client
上,我正在通过tcp
发送文本框中编写的字符串,并且服务器收到了该字符串
但当我尝试发送另一个字符串时,它失败了,没有任何异常,客户端应用程序将无限期挂起
这里有什么问题?查看您提供的代码,服务器仅尝试从客户端读取一条消息,因此需要将其放入一个循环中,从客户端读取多条传入消息,处理消息并发送响应,然后获取更多消息
还要注意,服务器当前只希望连接一个客户机,处理该客户机,然后关闭
客户机的设置与示例中的基本相同,因此您不能在不修改另一个客户机的情况下修改其中一个客户机的工作方式。服务器应始终处于侦听模式,即服务器代码应位于while循环中,以便它可以连续接受客户机。您的服务器将接受一个客户端,然后自行关闭。因此,如果单击“客户端”按钮,新客户端将尝试连接到服务器,但现在服务器将不可用 虽然这不是您的主要问题:TCP/IP是基于流的,而不是基于消息的。这样的代码有致命的缺陷:您可能永远不会假设对Receive
的特定调用接收特定数量的字节。您可以确定的是,如果客户端写入N
字节,则Receive
调用的某些组合最终将接收所有N
字节。这样的代码在本地套接字上的测试设置中可以很好地工作,而在实际网络中使用时会严重失败。
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();
}