尝试与 TcpClient 连接时的套接字异常
本文关键字:套接字 异常 连接 TcpClient | 更新日期: 2023-09-27 18:32:27
当我尝试创建一个新TcpClient
时,我得到了一个SocketException
,这是我的代码:
public void TcpOpenConnection()
{
// The next line is where the exception is occurring.
tcpClient = new TcpClient(ipAddress, port);
connected = true;
}
我已经检查以确保端口在cmd中打开netstat -a
,我什至制作了另一个功能来检查端口是否打开:
public static bool PortCheck(int port)
{
bool portOpen = false;
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfo = ipGlobalProperties.GetActiveTcpConnections();
foreach (var tcpConn in tcpConnInfo)
{
if (tcpConn.LocalEndPoint.Port == port)
{
portOpen = true;
break;
}
}
return portOpen;
}
返回 true。我得到的异常是SocketException
,它说我尝试连接的机器正在主动拒绝连接。这里可能有什么问题?我也尝试过其他端口,但没有运气。
如果您需要更多信息,请询问,我很乐意提供更多。
我得到的异常是
SocketException
,它说我尝试连接的机器正在主动拒绝连接。
这可能表明目标主机未侦听端口,这可能是由多种原因引起的:
- 服务器网络的路由器端口转发不正确
- 路由器的防火墙/服务器的防火墙阻止了连接
- 服务器和客户端未使用相同的端口
- 服务器配置错误
这样的例子不胜枚举...但从本质上讲,此错误意味着服务器不允许连接。
如果端口已打开并且您尝试连接到。您获得套接字异常是因为没有用于获取客户端连接的内容。
因此,您需要在此端口上托管一个Tcplistner。
static void StartServer()
{
int port = 150;
TcpListener listner = new TcpListener(IPAddress.Any, port);
listner.Start();
// This line waits the client connection.
TcpClient remote_client = listner.AcceptTcpClient();
// do something with remote_client.
}
您可以连接到。
static void StartClient()
{
int port = 150;
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpClient client = new TcpClient();
client.Connect(ip, port);
// Do something with client.
}