我尝试过使用Socket和TcpClient功能,发送后我无法接收数据。
我正在连接时钟设备,目标是向它发送一些命令并从中接收一些响应。该命令由设备识别,并应根据它检索数据。
所以我尝试使用以下代码的套接字:
private static string IP_ADDRESS = "10.0.0.20";
private static Int32 IP_PORT = 5010;
private static string TEXT_TO_SEND = "(1,software)";
static void Main(string[] args)
{
Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(IP_ADDRESS);
IPEndPoint ipEnd = new IPEndPoint(ip, IP_PORT);
mySocket.Connect(ipEnd);
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(TEXT_TO_SEND);
mySocket.Send(bytesToSend, 0, bytesToSend.Length, SocketFlags.None);
Console.WriteLine("Sending : " + TEXT_TO_SEND);
byte[] b = new byte[100];
int k = mySocket.Receive(b);
string text_received = Encoding.ASCII.GetString(b, 0, k);
// ---- NEVER REACHES HERE ----
Console.WriteLine("Receiving : " + text_received);
}
并尝试使用TcpClient。
private static string IP_ADDRESS = "10.0.0.20";
private static Int32 IP_PORT = 5010;
private static string TEXT_TO_SEND = "(1,software)";
static void Main(string[] args)
{
TcpClient client = new TcpClient(IP_ADDRESS, IP_PORT);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(TEXT_TO_SEND);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
nwStream.Flush();
Console.WriteLine("Sending : " + TEXT_TO_SEND);
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
string text_received = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);
// ---- NEVER REACHES HERE ----
Console.WriteLine("Receiving : " + text_received);
}
我没有收到错误,在调试时我清楚地看到两个代码都成功连接到机器(提供了IP和端口),但是没有检索到任何数据。