无法通过TCP连接到同一程序的其他实例

时间:2012-02-01 09:02:21

标签: c# tcp

我知道此事可能已被问过一千次,但我似乎无法找到有关我案件的任何具体信息。

我有一个C#客户端程序,必须通过LAN连接到客户端的其他实例。要将一个客户端连接到另一个客户端,我使用TcpListener / TcpClient aproach。这两个实例都有一个监听器,并且能够创建一个新的客户端来连接/监听彼此(它独立于哪个实例启动了连接)。

要创建侦听器,我使用以下代码:

// In the constructor:
listener = new TcpListener(IPAddress.Any, 32842);
listenThread = new Thread((ThreadStart)ListenForConnections);
listenThread.Name = "ListenThread";
listenThread.IsBackground = true;
listenThread.Start();

// Listening for connections:
private void ListenForConnections()
{
    listener.Start();
    Console.WriteLine("Started listening for connections");
    for (; ; )
    {
        if (listener.Pending())
        {
            using (TcpClient client = listener.AcceptTcpClient())
            {
                // My own layer over the TcpClient.
                AsyncTCPClient other = new AsyncTCPClient(client);
                Console.WriteLine("Connection from " + client.Client.RemoteEndPoint);
                other.Received += DataReceived;
                other.Exception += ExceptionOccurred;
                connections.Add("Player", other);
                other.Start();
            }
        }
        else
        {
            Thread.Sleep(5);
        }
    }
}

要创建并连接到另一个客户端,我使用以下代码:

public void Connect(IPEndPoint other)
{
    if (socket == null)
    {
        socket = new TcpClient(AddressFamily.InterNetwork);
        socket.Client.ReceiveBufferSize = 2 * 1024 * 1024;
    }
    // Should force-close the socket after 5 seconds if it can't be closed automatically.
    socket.LingerState = new LingerOption(true, 5);
    socket.BeginConnect(other.Address, other.Port, ConnectionCallback, other);
    IsConnecting = true;
}

作为BeginConnect参数提供的ConnectionCallback如下所示:

private void ConnectionCallback(IAsyncResult result)
{
    IsConnecting = false;
    IsConnected = socket.Connected;
    if (IsConnected)
    {
        IPEndPoint connectedTo = (IPEndPoint)result.AsyncState;
        stream = socket.GetStream();
        if (Connected != null)
        {
            Connected(this, null);
        }
    }
    else
    {
        if (Exception != null)
        {
            RaiseException(new Exception("Unable to connect to host"));
        }
    }
}

但是,每次进入回调时,TcpClient都无法连接到另一个实例,并且抛出了Exception事件。现在我在互联网(Google)上搜索时发现,它可能与连接两侧的防火墙有关。但我已经测试了所有防火墙,所以这不可能。

1 个答案:

答案 0 :(得分:2)

我没有看到在回调中调用Socket.EndConnect()。 在MSDN中看到这个: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.endconnect.aspx