繁体   English   中英

是否可以从服务器连接客户端

[英]Is it possible to connect with client from server

我正在使用C#编写TCP客户端服务器软件。 我希望客户端在服务器启动后立即自动与服务器连接。 要执行此任务,客户端可能需要知道服务器是否已启动。 但是怎么可能呢?

我的情况:同一局域网中有一个客户端和一台服务器。 每个人都知道另一人的IP地址。 这是在它们之间建立连接的代码部分:

服务器端:

// Starting the Server ...
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();

...

// Listening for client's connection in a thread ...
while (true)
{
    clientSocket = serverSocket.AcceptTcpClient();
    msg(" The client connected");
}

...

客户端:

// Here, client makes connection to the server when user clicks a button
clientSocket.Connect("192.168.1.1", "8888");

...

似乎可能的解决方案之一如下:客户端应“轮询”服务器,即客户端必须尝试定期连接到服务器,直到建立连接为止。

要指定“连接”操作的超时,请考虑使用TcpClient.BeginConnect方法和结果的IAsyncResult.AsyncWaitHandle属性来等待“超时事件”。 让我们介绍一个工厂来封装所描述的功能:

internal static class TcpClientFactory
{
    public static bool TryConnect(string host, int port, TimeSpan timeout, out TcpClient resultClient)
    {
        var client = new TcpClient();
        var asyncResult = client.BeginConnect(host, port, null, null);

        var success = asyncResult.AsyncWaitHandle.WaitOne(timeout);
        if (!success)
        {
            resultClient = default(TcpClient);
            return false;
        }

        client.EndConnect(asyncResult);
        resultClient = client;
        return true;
    }
}

使用工厂的客户端代码如下所示:

var timeout = TimeSpan.FromSeconds(3);
TcpClient client;
do
{
    Console.WriteLine("Attempting to connect...");
}
while (!TcpClientFactory.TryConnect("host here", port here, timeout, out client));

// Here the connected "client" instance can be used...

另外,请参考以下问题: 如何为TcpClient设置超时?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM