【发布时间】:2021-10-26 11:20:18
【问题描述】:
当我将消息发送到客户端并尝试使用 if 语句检查它时,它不等于我从服务器发送的消息。
我想做的是:我想发送关键字(这里是便便)并在客户端使用 if 语句检查它。 如果它在 if 语句中找到该关键字,我想执行一些代码。
例如:
客户端代码:
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",8001);
Console.WriteLine("Connected");
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
while(true)
{
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
{
var msg = Convert.ToChar(bb[i]).ToString();
if(msg == "poop")
{
Console.WriteLine("Poop executed.");
}
}
}
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
服务器代码(当控制台读取我的输入时,我输入“poop”):
try {
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
TcpListener myList=new TcpListener(ipAd,8001);
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);
ASCIIEncoding asen=new ASCIIEncoding();
while(true)
{
Console.Write("Msg to send: ");
var f = Console.ReadLine();
s.Send(asen.GetBytes(f));
}
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
【问题讨论】:
-
TCP/IP 正在流式传输,因此您不能依赖完整的消息接收
标签: c# tcp tcpclient tcplistener