我无法连接简单的客户端和简单的服务器。当我运行服务器时似乎没有任何问题,但是当我尝试向客户端发送数据时,它会抛出一个异常,说它在超时期限内没有连接。
这是我正在使用的服务器代码:
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);
}
}
任何建议都会很棒。
答案 0 :(得分:1)
我建议查看TcpListener和TcpClient类,而不是使用套接字.. Tcp *类为你做了所有这些事情
答案 1 :(得分:1)
获取公共IP意味着您在NAT设备(如简单的家庭路由器)之后。您是否确保设备将TCP连接转发到端口5656到服务器计算机并且还配置了服务器的防火墙?
答案 2 :(得分:1)
请尝试此代码。也许没有资源泄漏,它会更好地工作:
public void server()
{
try
{
byte[] bytes = new byte[1024];
IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs
IPEndPoint directionPort = new IPEndPoint(direction, 5656);
using (Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socketServer.Bind(directionPort);
socketServer.Listen(100);
while (true)
{
using (Socket client = socketServer.Accept())
{
int bytesReceived = client.Receive(bytes);
String 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);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public string getIPExternal()
{
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
string direction;
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
direction = reader.ReadToEnd();
}
}
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
return direction.Substring(first, last - first);
}
客户:
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);
using (Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socketClient.Connect(directionPort);
socketClient.Send(bytesSend);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
答案 3 :(得分:1)
这里有很多失败的空间。除非您手动输入,否则客户端能够猜测服务器IP地址的几率很小。它也必须在另一个网络上运行。如果您使用两台靠近的计算机进行测试,请考虑使用本地IP地址,如果您在同一台计算机上进行测试,则考虑使用127.0.0.1。并且防火墙几乎肯定会阻止端口号。你必须为它做一个明确的例外。