我使用TcpListener和TcpClient在C#中编写了服务器和客户端程序,我希望它们交换字符串。如果两台PC都连接到同一网络并且我使用服务器的本地地址,则可以使用,但是当PC连接到其他网络并且使用公共地址时,会出现以下错误:
Exception: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at Server___Network_Class.Program.Main(String[] args) in D:\Server - Network Class\Program.cs:line 18
此错误涉及第18行,即myList.Start();。但我不知道为什么会引发此异常。我打开了路由器端口,并正确设置了Windows防火墙...这是我编写的服务器和客户端代码:
服务器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server___Network_Class {
class Program {
static void Main(string[] args) {
try {
IPAddress ipAddress = IPAddress.Parse("146.241.31.193"); //That's the public IP
//Initialize the listener
TcpListener myList = new TcpListener(ipAddress, 51328);
//Start listening the selected port
myList.Start();
Socket socket = myList.AcceptSocket();
ASCIIEncoding asen = new ASCIIEncoding();
socket.Send(asen.GetBytes("Can you read this?"));
socket.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}
客户
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client___Class_Network {
class Program {
static void Main(string[] args) {
try {
//Inizializzo il client
TcpClient client = new TcpClient();
//Cerco di connettermi al server
client.Connect("146.241.31.193", 51328); //IP and Port i want to connect to
//Stream sul quale inviare e ricevere i dati dal server
NetworkStream stream = client.GetStream();
Byte[] bytesRecived = new Byte[256];
int totBytesRecived = stream.Read(bytesRecived, 0, bytesRecived.Length);
String stringData = System.Text.Encoding.ASCII.GetString(bytesRecived, 0, totBytesRecived);
Console.Write(stringData);
client.Close();
}
catch (Exception e) {
Console.WriteLine("Exception: " + e);
}
Console.ReadKey();
}
}
}
只有服务器程序会抛出该异常,客户端似乎是工作文件...
你能帮我解决这个问题吗?我(几乎)在网上搜索了所有内容,但找不到任何有用的答案。提前致谢!
公共IP地址是在Windows机器上还是仅在路由器上真正可用?
检查ipconfig
在“命令行”窗口中运行时是否显示公共地址。我的猜测是,你需要在路由器中设置NAT端口转发,并将应用程序设置为侦听路由器提供给Windows计算机的IP地址。这样的IP地址通常以10.
或开头192.
。
尝试将你的服务器绑定到该地址0.0.0.0
。这样,它将监听你所有的网卡(WiFi,以太网),而无需进行任何配置。
谢谢,我发现了问题。我不知道为什么,但是网站whatismyipaddress.com给我的IP地址不正确。在客户端程序中,我输入了在路由器配置页面上找到的IP(这是一个不同的IP),并且该IP有效。
我确定whatismyipaddress也正确。它是您的外部IP。如果TCP客户端希望从外部访问您的服务器,则这一点很重要。
不,还有其他问题...昨天,我尝试与具有相同ISP的朋友建立联系,并且它能够与我通信。但是我给另一个拥有不同ISP的朋友打了电话,他无法连接到我的服务器...这不是很奇怪吗?你知道为什么吗?
这可能是由于其侧面的端口限制所致。我的直觉是,这不是ISP或您的应用程序的区别。也许使用更标准的端口而不是51328。如果在启动服务器时出现异常,则可能是因为该端口被计算机上的某物占用了。不要使用端口80,因为Windows内核经常保留它。祝你好运!