C# 测试2台远程服务器之间的套接字连接

C# 测试2台远程服务器之间的套接字连接,c#,.net,wpf,sockets,remote-server,C#,.net,Wpf,Sockets,Remote Server,我开发了一个C#WPF监控应用程序,它可以检查与其他服务器的连接。在远程服务器上,我们有一个在特定端口上运行的应用程序服务。如果我们只是将telnet连接到该服务器的端口,就会看到服务名称正在运行。 我正忙着将我的概念验证应用程序转换为WPF应用程序,以便它使用端点和Socket.BeginConnect等来不断检查远程服务器上运行的连接和服务,这是100%有效的。 但是,我想监控几个服务器,每个服务器都检查与其他远程服务器的连接,因此我希望能够在一个远程服务器到另一个远程服务器之间运行测试,并

我开发了一个C#WPF监控应用程序,它可以检查与其他服务器的连接。在远程服务器上,我们有一个在特定端口上运行的应用程序服务。如果我们只是将telnet连接到该服务器的端口,就会看到服务名称正在运行。 我正忙着将我的概念验证应用程序转换为WPF应用程序,以便它使用端点和Socket.BeginConnect等来不断检查远程服务器上运行的连接和服务,这是100%有效的。 但是,我想监控几个服务器,每个服务器都检查与其他远程服务器的连接,因此我希望能够在一个远程服务器到另一个远程服务器之间运行测试,并在我的WPF应用程序上本地获取结果。 解决这个问题的一种方法是在远程服务器上运行一个应用程序,收集这些信息,然后访问这些数据,但如果可能的话,我希望能够避免这种情况

这是我的代码——目前非常原始,非常符合概念。 例如,我想在网络上的笔记本电脑上运行此应用程序,并监视其他服务器:

// CPU Usage ----------------------------------------------------------
private string getUsageCPU()
{
    cpuCounter = new PerformanceCounter();

    cpuCounter.CategoryName = "Processor";
    cpuCounter.CounterName = "% Processor Time";
    cpuCounter.InstanceName = "_Total";

    return cpuCounter.NextValue() + "%";
}
// --------------------------------------------------------------------

// Memory Usage -------------------------------------------------------
private string getUsageRAM()
{
    ramCounter = new PerformanceCounter("Memory", "Available MBytes");
    return ramCounter.NextValue() + " MB";
}
// --------------------------------------------------------------------

// Service Status -----------------------------------------------------
private string getServicesStatus(string service)
{
    string status = "";
    ServiceController sc = new ServiceController(service);
    try
    {
        status = sc.Status.ToString();
    }
    catch (Exception ex)
    {
        status = "not found: " + ex.Message;
    }
    return status;
}
// --------------------------------------------------------------------

// Connectivity Test --------------------------------------------------
private string getTelnetResponse(string host, int port)
{
    string result = "";
    IPAddress ipAddress = null;

    try {
        IPHostEntry ipHostInfo = Dns.GetHostEntry(host);
        if (!IPAddress.TryParse(host, out ipAddress))
        {
            ipAddress = ipHostInfo.AddressList[0];
        }
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

        // Need to run this from the Server we are monitoring not from where the application is running.
        // Create a TCP/IP socket.
        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.
        Send(client, "This is a test<EOF>");
        sendDone.WaitOne();

        // Receive the response from the remote device.
        Receive(client);
        receiveDone.WaitOne();

        // Write the response to the console.
        result = String.Format("Response received : {0}", response);

        // Release the socket.
        client.Shutdown(SocketShutdown.Both);
        client.Close();
    }
    catch (Exception e)
    {
        labelValueTelnet.Text = (e.ToString());
    }

    return result;
}

// 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;

// 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();
}

private void ConnectCallback(IAsyncResult ar)
{
    try
    {
        // Retrieve the socket from the state object.
        Socket client = (Socket)ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        ////labelValueTelnet.Text = String.Format("Socket connected to {0}", client.RemoteEndPoint.ToString());

        // Signal that the connection has been made.
        connectDone.Set();
    }
    catch (Exception)
    {
        //labelValueTelnet.Text = (e.ToString());
    }
}

private 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)
    {
        labelValueTelnet.Text = (e.ToString());
    }
}

private 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.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

            // Get the rest of the data.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        else
       {
           // 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)
    {
        labelValueTelnet.Text = (e.ToString());
    }
}

private 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 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);
        //labelValueTelnet.Text = String.Format("Sent {0} bytes to server.", bytesSent);

        // Signal that all bytes have been sent.
        sendDone.Set();
    }
    catch (Exception e)
    {
        labelValueTelnet.Text = (e.ToString());
    }
}
// --------------------------------------------------------------------
//CPU使用率----------------------------------------------------------
私有字符串getUsageCPU()
{
cpuCounter=新性能计数器();
cpuCounter.CategoryName=“处理器”;
cpuCounter.CounterName=“%Processor Time”;
cpuCounter.InstanceName=“_Total”;
返回cpuCounter.NextValue()+“%”;
}
// --------------------------------------------------------------------
//内存使用-------------------------------------------------------
私有字符串getUsageRAM()
{
ramCounter=新性能计数器(“内存”、“可用MB”);
返回ramCounter.NextValue()+“MB”;
}
// --------------------------------------------------------------------
//服务状态-----------------------------------------------------
私有字符串getServicesStatus(字符串服务)
{
字符串状态=”;
ServiceController sc=新的ServiceController(服务);
尝试
{
status=sc.status.ToString();
}
捕获(例外情况除外)
{
status=“未找到:”+ex.消息;
}
返回状态;
}
// --------------------------------------------------------------------
//连通性测试--------------------------------------------------
私有字符串getTelnetResponse(字符串主机,int端口)
{
字符串结果=”;
IPAddress IPAddress=null;
试一试{
IPHostEntry ipHostInfo=Dns.GetHostEntry(主机);
if(!IPAddress.TryParse(主机,输出IPAddress))
{
ipAddress=ipHostInfo.AddressList[0];
}
IPEndPoint remoteEP=新IPEndPoint(ipAddress,端口);
//需要从我们正在监视的服务器上运行,而不是从应用程序运行的地方运行。
//创建TCP/IP套接字。
Socket client=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
//连接到远程端点。
BeginConnect(remoteEP,新的异步回调(ConnectCallback),client);
connectDone.WaitOne();
//将测试数据发送到远程设备。
发送(客户端,“这是一个测试”);
sendDone.WaitOne();
//从远程设备接收响应。
接收(客户);
receiveDone.WaitOne();
//将响应写入控制台。
result=String.Format(“收到的响应:{0}”,响应);
//松开插座。
client.Shutdown(SocketShutdown.Both);
client.Close();
}
捕获(例外e)
{
labelValueTelnet.Text=(e.ToString());
}
返回结果;
}
//ManualResetEvent实例信号完成。
专用静态手动复位事件连接完成=新手动复位事件(错误);
专用静态手动复位事件sendDone=新手动复位事件(false);
private static ManualResetEvent receiveDone=新的ManualResetEvent(错误);
//来自远程设备的响应。
私有静态字符串响应=String.Empty;
//用于从远程设备接收数据的状态对象。
公共类状态对象
{
//客户端套接字。
公共套接字工作组=null;
//接收缓冲区的大小。
public const int BufferSize=256;
//接收缓冲区。
公共字节[]缓冲区=新字节[BufferSize];
//接收到的数据字符串。
公共StringBuilder sb=新StringBuilder();
}
私有无效连接回调(IAsyncResult ar)
{
尝试
{
//从状态对象检索套接字。
套接字客户端=(套接字)ar.AsyncState;
//完成连接。
客户端.EndConnect(ar);
////labelValueTelnet.Text=String.Format(“连接到{0}的套接字”,client.RemoteEndPoint.ToString());
//表示已建立连接的信号。
connectDone.Set();
}
捕获(例外)
{
//labelValueTelnet.Text=(e.ToString());
}
}
私有void接收(套接字客户端)
{
尝试
{
//创建状态对象。
StateObject状态=新的StateObject();
state.workSocket=客户端;
//开始从远程设备接收数据。
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReceiveCallback),state);
}
捕获(例外e)
{
labelValueTelnet.Text=(e.ToString());
}
}
私有void ReceiveCallback(IAsyncResult ar)
{
尝试
{
//检索状态对象和客户端套接字
//从异步状态对象。
StateObject状态=(StateObject)ar.AsyncState;
套接字客户端=state.workSocket;
//从远程设备读取数据。
int bytesRead=client.EndReceive(ar);
如果(字节读取>0)
{
//可能会有更多数据,因此请存储到目前为止收到的数据。
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
//获取其余的数据。
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,新Asy