我正尝试使用套接字连接到应用程序。无法从服务器接收消息的套接字
应用程序使用端口6100进行通信。 我能够将消息发送到应用程序,但无法接收任何消息。
这是我的代码,请让我知道如果我做错了什么。
public void Connect2(string host, int port, string cmd)
{
byte[] bytes = new byte[10024];
IPAddress[] IPs = Dns.GetHostAddresses(host);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
s.SendTimeout = 100;
Console.WriteLine("Establishing Connection to {0}",
host);
try
{
s.Connect(IPs[0], port);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
byte[] sendBites = System.Text.Encoding.ASCII.GetBytes(cmd);
int bytesSent = s.Send(sendBites);
int bytesRec = s.Receive(bytes);
s.ReceiveFrom(bytes, ref tmpRemote);
MessageBox.Show(s.ReceiveBufferSize.ToString());
MessageBox.Show(Encoding.ASCII.GetString(bytes, 0, bytesRec));
s.Shutdown(SocketShutdown.Both);
s.Close();
}
此代码已损坏。它无法检查来自'Receive'的返回值,它告诉你有多少个字节已经放入缓冲区。 TCP是字节流。如果你想要“消息传递”,你可以自己在TCP之上实现消息组帧,或者移动到已经提供消息的更高层抽象。 –