我无法连接简单的客户端和简单的服务器。当我运行服务器时,似乎没有任何问题,但是当我尝试向客户端发送数据时,它会引发异常,说它在超时期限内未连接。.NET中的套接字无法连接
这里是我使用的服务器代码:
public void server()
{
try
{
byte[] bytes = new byte[1024];
int bytesReceived = 0;
String message = "";
IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs
IPEndPoint directionPort = new IPEndPoint(direction, 5656);
Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(directionPort);
socketServer.Listen(100);
while (true)
{
Socket client = socketServer.Accept();
bytesReceived = client.Receive(bytes);
message = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesReceived);
editMultiline.Invoke(new writeMessageDelegate(writeMessage), new object[] { message, "client"}); //Ignore this, it is just to show the info in a textbox because the server code runs in a diferent thread
client.Shutdown(SocketShutdown.Both);
client.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
这样,我从机器中获得的公网IP在其上运行程序:
public string getIPExternal()
{
string direction;
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
direction = stream.ReadToEnd();
stream.Close();
response.Close();
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
这里是我的客户端代码:
public void client(string directionIP, string message) //directionIP is the IP from the computer to which i want to get connected
{
try
{
byte[] bytesSend = System.Text.Encoding.Unicode.GetBytes(message);
IPAddress direction = IPAddress.Parse(directionIP);
IPEndPoint directionPort = new IPEndPoint(direction, 5656);
Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketClient.Connect(directionPort);
socketClient.Send(bytesSend);
socketClient.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
任何建议都会很棒。
究竟在哪里抛出异常? – caesay 2010-02-28 03:26:44
我催促你停止显示ex.Message。改用ex.ToString()。 – 2010-02-28 03:29:34
@ezgar,我早些时候回答过,但在测试代码后删除了它,因为它解决了不同的问题。正如sniperX所问,抛出的异常究竟在哪里以及异常信息是什么?我无法复制类似的错误,因为我的设置没有公开的IP,我可以通过'dyndns.org'进行检索。 – 2010-02-28 04:56:05