开发者

program is listening on TCP port, but connections to that port are refused

I have a simple program I'm developing to perform some bandwidth tests on remote computers my company controls at our client sites. One copy of the program goes on a remote computer and is told to listen on a specified port. Another copy of the same program is then 开发者_JS百科told to connect to the listening computer, then send a serialized object with a message of known length, random contents. The transfer is timed and the results sent back to the originating machine.

It works fine over the loopback interface; two copies of the program going, one listening on a part, the other connecting to that same port (in a shared manner) and sending the data. However, when I move the "remote" side of this test to a different test machine on the same intranet, even though the program says it's "listening" for its connection, the port cannot be connected to by the program on my dev machine. I get the standard error "No connection could be made because the target machine actively refused it".

There are no active firewalls between these two computers, including Windows Firewall. I can create other types of remote connections such as VNC.

Here are the relevant code snippets:

Listening for a connection:

    public void BeginListeningAsServer()
    {
        if (Listener != null) Listener.Stop();
        if (ListenerThread != null) ListenerThread.Join();
        Listener = new TcpListener(RemoteAddress, RemotePort);
        Listener.Start();
        Listening = true;
        ListenerThread = new Thread(ListenForConnections);
        ListenerThread.Start();
    }

    private void ListenForConnections()
    {
        while (Listening)
        {
            if (Listener.Pending())
                Listener.BeginAcceptTcpClient(HandleIncomingClient, null);
        }
    }

    private void HandleIncomingClient(IAsyncResult ar)
    {
        var client = Listener.EndAcceptTcpClient(ar);
        var thread = new Thread(c => HandleIncomingClientMessage((TcpClient)c));
        HandlerThreads.Add(thread);
        Clients.Add(client);
        thread.Start(client);
    }

Connecting to this listening program:

    public void ConnectAsClient()
    {
        var client = new TcpClient();
        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        client.Connect(RemoteAddress, RemotePort); //this line fails
        Clients.Add(client);
    }


The way you star your listener is a bit off. You don't need to specify the Address, only the port.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜