我想从我的电脑上连接服务器。但它不起作用。它总是显示错误。我也想从客户端向服务器发送消息,所以请帮助我,我该怎么办?
系统在尝试使用a时检测到无效指针地址 调用中的指针参数
我的代码是:
public partial class Form1 : Form
{
Socket socket;
IPAddress ipAddress;
string address = "192.168.1.203";
public Form1()
{
InitializeComponent();
}
private void btnStartServer_Click(object sender, EventArgs e)
{
SocketPermission socketPermission = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts);
socketPermission.Demand();
IPHostEntry ipHOst = Dns.GetHostEntry("");
ipAddress = ipHOst.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(address), 4532);
socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = false;
socket.Connect(ipEndPoint);
txtClinet1.Text = "Socket connected to " + socket.RemoteEndPoint.ToString();
}
}
答案 0 :(得分:1)
是什么让你认为AddressList [0]是你可以使用的?根据DOCS,您必须遍历列表,直到找到正确的列表。
例如:
private void button1_Click(object sender, EventArgs e)
{
SocketPermission socketPermission = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "", SocketPermission.AllPorts);
socketPermission.Demand();
IPHostEntry ipHOst = Dns.GetHostEntry("");
for (int i = 0; i < ipHOst.AddressList.Length; i++)
{
ipAddress = ipHOst.AddressList[i];
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(address), 4532);
socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = false;
try
{
socket.Connect(ipEndPoint);
MessageBox.Show("Socket connected to " + socket.RemoteEndPoint.ToString());
break;
}
catch (Exception eX)
{
MessageBox.Show(eX.Message);
}
}
}
在我的计算机中,它连接到第三个地址AddressList[2];