我知道这个问题以前可能被问过一千次,但我似乎找不到关于我的案例的任何具体信息。
我有一个 C# 客户端程序,它必须通过 LAN 连接到客户端的其他实例。为了将一个客户端连接到另一个客户端,我使用了 TcpListener/TcpClient 方法。这两个实例都有一个监听器,并且能够创建一个新的客户端来相互连接/监听(它独立于哪个实例启动连接)。
为了创建监听器,我使用了以下代码:
// 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) 上搜索时发现,它可能与连接两侧的防火墙有关。但我已经在关闭所有防火墙的情况下对其进行了测试,所以这不可能。
最佳答案
我没有看到 Socket.EndConnect() 在回调中被调用。 在 MSDN 中看到这个: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.endconnect.aspx
关于c# - 无法通过 TCP 连接到同一程序的其他实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9093165/