我是C#编程的新手,我正在尝试编写TCP客户端,该TCP客户端将通过HEAX代码将HEX代码发送到服务器,从服务器读取一些元数据。我设法与服务器但无法发送十六进制代码。请您看看我在这里缺少的东西。
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;
public class clnt
{
public static void Main()
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting...");
tcpclnt.Connect("192.168.80.128", 557);
// use the ip address as in the server program
Console.WriteLine("Connected!");
Console.WriteLine("Sending Hex Code...");
string str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
var data = new byte[] { 0xCF, 0xC4 };
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 e)
{
Console.WriteLine("Opps " + e.StackTrace);
}
}
}
//C++ code
int main()
{
client.Initialize("192.168.80.128", 557);
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string xid = U8("NASA_Arnold_AFB_Airshow");
std::vector<std::uint8_t> command = {0xCF, 0xC4};
command.push_back(static_cast<std::uint8_t>(xid.length()));
command.insert(command.end(), xid.begin(), xid.end());
std::cout << command.size() << std::endl;
client.Correspond(command, 10);
std::this_thread::sleep_for(std::chrono::seconds(3));
command.clear();
command = {0xC8, 0xC3};
std::cout << client.Response().size() << std::endl;
std::vector<std::uint8_t> idhandle(client.Response().begin() + 2, client.Response().end());
command.insert(command.end(), idhandle.begin(), idhandle.end());
client.Correspond(command, 3);
std::this_thread::sleep_for(std::chrono::seconds(3));
for(auto element : client.Response())
std::cout << static_cast<int>(element) << std::endl;
std::uint8_t size = client.Response().back();
std::cout << "size of xid:" << static_cast<int>(size) << std::endl;
client.ReadN(size);
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << std::string(client.Response().begin(), client.Response().end()) << std::endl;
command.clear();
command = {0xC8, 0x4A};
command.insert(command.end(), idhandle.begin(), idhandle.end());
std::cout << idhandle.size() << std::endl;
for(auto element : idhandle)
std::cout << static_cast<int>(element) << std::endl;
client.Correspond(command, 97);
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << std::string(client.Response().begin(), client.Response().end()) << std::endl;
std::getchar();
return 0;
}
如果我正确理解,则您的特定字节在数组data
中。但是您不在代码中使用它。
看来您错过了stm.Write(data, 0, data.Length)
之类的东西发送字节0xcf和0xc4
您的代码提示输入:
string str = Console.ReadLine();
然后从此输入中获取字节:
byte[] ba = asen.GetBytes(str);
最后将这些字节发送到流:
stm.Write(ba, 0, ba.Length);
您是否在提示下输入任何内容?如果没有,那么就不会发送任何字节。相反,如果您打算发送var data = new byte[] { 0xCF, 0xC4 };
,则需要使用
stm.Write(data, 0, data.Length);