我正在使用C#编写的应用程序,通过IP连接到我们的一些设备。应用程序连接到设备就好了,我们可以发送配置它所需的命令。我遇到的问题是在大约40秒到一分钟没有发送任何命令后连接断开连接。我想知道我能做些什么来保持套接字存活至少几分钟。需要一些关于实施心跳的指导,感谢任何帮助。
以下是我们正在使用的代码。
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Globalization;
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
// The port number for the remote device.
//private const int port = 1000;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
static Socket client;
internal static Boolean StartClient(string ip_address, int port)
{
// Connect to a remote device.
Boolean bRtnValue = false;
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
//IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = IPAddress.Parse(ip_address);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
string msg = ((char)2) + "S" + (char)13;
Send(client, msg);
//sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
//receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
bRtnValue = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
//return value
return bRtnValue;
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Clear();
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + state.sb.ToString());
//54A111503000000000017D8857E3
//IDSSSSSSSSSSSSSSSSTTTTCCCCKK 017D
if (state.sb.ToString(0, 2) == "54")
{
string hexString = state.sb.ToString(18, 4);
int num = Int32.Parse(hexString, NumberStyles.HexNumber);
double degreesF = ((double)num / 16.0) * 9.0 / 5.0 + 32.0;
string f = degreesF.ToString("#.#");
Console.WriteLine(" " + f);
}
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
Console.WriteLine("data");
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
internal void StartListening(string ip_address, int port)
{
StartClient(ip_address, port);
}
答案 0 :(得分:2)
当没有数据要发送时,你需要实现一个模拟心跳的计时器,即。在您发送的最后一个数据包之后,您将启动计时器几秒钟。如果您在此之前要发送数据,则取消它,发送数据并再次重新启动计时器。如果定时器超时,则发送一个虚拟数据包并重新启动定时器,以便在相同的超时时间后再次执行此操作。
答案 1 :(得分:0)
这就是所谓的超时,这是(据我所知)当连接的另一端中止,断开连接或以其他方式完全停止传输数据时处理的每个网络协议的重要特征。毕竟,没有办法传输数据包说'#34;我的猫只敲了我的路由器,中止连接。"
您需要做的是,如评论中所述,通过网络发送定期的无操作(即无操作)命令,以防止超时。这样的包被称为"心跳"或" keepalive"信号,应该比实际超时更频繁地发送,以防丢失或迟到。这最好通过启动一个seondary线程来完成,当连接被标记为打开时,它只会发送心跳。