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

时间:2015-03-18 15:45:24

标签: c# tcpclient tcplistener tcpsocket

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

我的情况: 同一LAN网络上有一个客户端和一个服务器。每个人都知道其他人的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");

...

1 个答案:

答案 0 :(得分:1)

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

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

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...

此外,请参阅此问题:How to set the timeout for a TcpClient?

相关问题