发送第二条消息,我想通过TCP/IP使用TCPClient
和TCPListner
类无法通过TCP/IP
下面的C#应用程序发送的消息是我的代码,我从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
和客户端应用程序挂起无限时间。
这里有什么问题?
虽然这不是您的主要问题:TCP/IP是基于流的,而不是基于消息的。像这样的代码是致命的缺陷:你可能永远不会假设对'Receive'的特定调用接收到特定数量的字节。您可以确定的是,如果客户端写入“N”个字节,则“接收”调用的某些组合最终将收到所有“N”个字节。像这样的代码可以在本地套接字上的测试设置中正常工作,并且在实际网络中工作时会失败。 –