gpt4 book ai didi

c# - 客户端未连接到服务器,而是获得了无效的指针地址

转载 作者:行者123 更新时间:2023-12-03 12:05:03 25 4
gpt4 key购买 nike

我想从我的电脑连接服务器。但它不起作用。它总是显示错误。我也想从客户端向服务器发送消息,所以请帮助我该怎么办?

The system detected an invalid pointer address in attempting to use a pointer argument in a call



我的代码是:
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();
}

}

最佳答案

是什么让您认为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];

关于c# - 客户端未连接到服务器,而是获得了无效的指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28192476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com