我正在尝试使用Tcp客户端读取服务器。要读取服务器,您需要发送命令。
命令(ASCII通信(:
Octet 001:SOH;Octet 002:访问代码:"0〃-阅读"1〃-需要"2〃-使现代化Octet 003:STX;Octet 004-135:用于常规通信服务器/读取器的命令,将半字节到半字节转换为ASCII码,包括CRC;Octet136:ETX;Octet 137:LRC;
简单响应:
Octet 001:STX;Octet 002-517:常规通信服务器/读取器的简单响应,将半字节转换为ASCII码,包括CRC;Octet 518:ETX;Octet 519:LRC;
我的Tcp客户端代码:
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 2180;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
//data = new Byte[256];
data = new Byte[9];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("n Press Enter to continue...");
Console.Read();
}
我的问题是,如何将这些命令转换为发送到服务器?我试过这个:
Connect("192.168.0.250", "0");
Connect("192.168.0.250", "1");
Connect("192.168.0.250", "2");
但没有服务器响应。
不确定,但试试这个:
try
{
TcpClient client = new TcpClient();
client.Connect(server, port);
byte[] data = new byte[256];
StringBuilder response = new StringBuilder();
NetworkStream stream = client.GetStream();
do
{
int bytes = stream.Read(data, 0, data.Length);
response.Append(Encoding.UTF8.GetString(data, 0, bytes));
}
while (stream.DataAvailable); // while data in stream
Console.WriteLine(response.ToString());
// close stream
stream.Close();
client.Close();
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.Message);
}
Console.WriteLine("End...");
Console.Read();
你可以看到我的回购https://github.com/AkumaWalker/ClientServer使用TCP聊天工作:
- 构建客户端和服务器控制台应用程序
- 打开调试文件夹
- 启动Server.exe
- 启动Client.exe,然后输入名称和消息=>所有客户端和服务器都将接收消息