我开发了C#中的TCP / IP Server侦听端口,GPS设备正在将数据发送到服务器。
最初,设备将IMEI号发送到服务器,服务器用01确认。设备收到确认后,会向服务器发送新的数据包。
我能够通过TCP服务器获取IMEI号码,并且在发送确认后,我无法从客户端接收新的数据包数据。我也在下面包含我的代码。请让我知道我错在哪里。
我已经使用hercules tcp服务器工具进行了测试,下一个数据包正在成功接收,但是从我的应用程序中它无法正常工作。
try
{
IPAddress ipAdress = IPAddress.Parse(ConfigurationManager.AppSettings["Server"].ToString());
// You can use local IP as far as you use the
//same in client
// Initializes the Listener
TcpListener myList = new TcpListener(ipAdress, int.Parse(ConfigurationManager.AppSettings["Port"].ToString()));
for (; ; )
{ // Run forever, accepting and servicing connections
//Start Listeneting at the specified port
myList.Start();
Console.WriteLine("Server running - Port: 8000");
Console.WriteLine("Local end point:" + myList.LocalEndpoint);
Console.WriteLine("Waiting for connections...");
Socket socket = myList.AcceptSocket();
// When accepted
Console.WriteLine("Connection accepted from " + socket.RemoteEndPoint);
byte[] b = new byte[1000];
int k = socket.Receive(b);
Console.WriteLine("echoed {0} bytes.", k);
Console.WriteLine("Reading IMEI....");
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
File.WriteAllText(@"C:\ClientFiles\testIMEI", hexStr);
ASCIIEncoding asen = new ASCIIEncoding();
string response = "01";
Console.WriteLine("Ackowledgement Data - " + response);
//
int sentBytes = socket.Send(asen.GetBytes(response));
Console.WriteLine("Acknowledgement data sent!\n");
int count = 0;
while (socket.Poll(-1, SelectMode.SelectRead))
{
b = new byte[1000];
k = socket.Receive(b);
if (k > 0)
{
count++;
Console.WriteLine("Reading Client Data - Count - " + count.ToString() + " and lenght " + k.ToString());
hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
File.WriteAllText(@"C:\ClientFiles\testData" + count.ToString(), hexStr);
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
myList.Stop();
}
catch (Exception ex)
{
File.WriteAllText(@"C:\ClientFiles\Error.txt", ex.Message + "****" + ex.InnerException);
}
答案 0 :(得分:0)
除了这些评论之外,我没有看到程序中的任何错误:
// Don't use the b.Length in this command:
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, b.Length));
// use k instead, the numbers actually read, not the length of the buffer.
string hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, k));
while (socket.Poll(-1, SelectMode.SelectRead))
{
// b has been allocated, don't need this
// b = new byte[1000];
k = socket.Receive(b);
if (k > 0)
{
count++;
Console.WriteLine("Reading Client Data - Count - " + count.ToString() + " and lenght " + k.ToString();
// use k not Length
hexStr = ConvertAsciiToHex(Encoding.ASCII.GetString(b, 0, k /*b.Length*/));
File.WriteAllText(@"C:\ClientFiles\testData" + count.ToString(), hexStr);
}
}
你知道Poll命令是否会返回?可能是它引发了一个错误而你错过了那一个。看看吧。