C# 发送ASCII消息
我有一台“Sysmex XP-300”机器,它通过TCP发送数据,我需要捕获这些数据并用ASCII回复,以验证是否收到了数据。 问题是,每次连接机器时,代码都会不停地回复“已连接”。我还需要回答ASCII,我的机器似乎没有收到。这是我的代码:C# 发送ASCII消息,c#,tcpserver,C#,Tcpserver,我有一台“Sysmex XP-300”机器,它通过TCP发送数据,我需要捕获这些数据并用ASCII回复,以验证是否收到了数据。 问题是,每次连接机器时,代码都会不停地回复“已连接”。我还需要回答ASCII,我的机器似乎没有收到。这是我的代码: class Program { static string ack = char.ConvertFromUtf32(6); byte[] byData = System.Text.Encoding.ASCII.GetBytes(ack);
class Program
{
static string ack = char.ConvertFromUtf32(6);
byte[] byData = System.Text.Encoding.ASCII.GetBytes(ack);
const int PORT_NO = 3001;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
TcpServer tcpServer = new TcpServer(SERVER_IP, 3001);
tcpServer.Connected += new TcpServer.TcpServerEventDlgt(OnConnected);
tcpServer.StartListening();
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
tcpServer.StopListening();
}
static void OnConnected(object sender, TcpServerEventArgs e)
{
// Handle the connection here by starting your own worker thread
// that handles communicating with the client.
Console.WriteLine("Connected.");
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(ack);// ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " );
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
我想你的问题是关于ASCII而不是ashii。在我看来,在OnConnect中,你是从服务器连接到服务器(
TcpClient(server\u IP,PORT\u NO)
),然后将ack
发送到自身而不是连接的客户端。这再次导致另一个OnConnect,该OnConnect对连接的无限循环执行相同的操作。我假设您要发送到的客户端位于TcpServerEventArgs e
中的某个位置。如果我键入:“e.ConnectionState”,则只显示“connection”和“server”