我有一个C#客户端和一个单独的服务器应用程序。当我在同一台计算机上执行两个时,无法连接到服务器。但是,当我尝试远程连接到服务器时,它总是以超时结束。我使用端口139,并尝试在多台计算机上运行服务器应用程序。我已经在一个对公众开放的服务器,我的私人PC和路由器将此端口转发到PC以及同一网络中的笔记本电脑的服务器上进行了尝试。 我一直在检查运行服务器的计算机是否正在使用netstat -an侦听端口,并在所有防火墙上设置了例外。 我在客户端上用于连接到服务器的代码:
static IPHostEntry ipHostInfo = Dns.GetHostEntry("xxx.xxx.xxx.xxx");
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
static Socket client = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
static private void ConnectToServer()
{
try
{
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine("Error: ", ex.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
我用来接受服务器上连接的代码:
static IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
static IPAddress ipAddress = ipHostInfo.AddressList[0];
static IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 139);
static Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Listening on: " + ipAddress);
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
正如我说的,当客户端和服务器应用程序都在同一台PC上执行时,这可以完美地工作。但是,如果它们在不同的计算机上,则客户端会在几秒钟内收到timout错误。
感谢您的帮助,谢谢。