IPAddress HostIP;
IPEndPoint point;
Socket socket;
bool flag = true;
Socket acceptedSocket;
int p=8000;
//声名委托
delegate void SetTextCallback(string text);
private void SetText(string text)
{
rtfShowMessage.AppendText(text + "");
}
//进程方法
private void Proccess()
{
if (acceptedSocket.Connected)
{
while (flag)
{
byte[] receiveByte = new byte[64];
acceptedSocket.Receive(receiveByte, receiveByte.Length, 0);
string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
this.Invoke(new SetTextCallback(SetText), new object[] { strInfo });
}
}
}
//启动
private void btnStart_Click(object sender, EventArgs e)
{
string hostName = Dns.GetHostName();//获得主机名
IPAddress[] me = Dns.GetHostAddresses(hostName); //获取IP地址列表
HostIP = me[0]; //取第一个IP地址
try
{
point = new IPEndPoint(HostIP, p);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(point);
socket.Listen(50);
acceptedSocket = socket.Accept();
Thread thread = new Thread(new ThreadStart(Proccess));
thread.Start();
label1.Text = "服务器已有链接!";
}
catch (Exception ex)
{
MessageBox.Show("服务器启动失败!" + ex.Message);
}
p++;
}
//发送
private void btnSendMessage_Click(object sender, EventArgs e)
{
try
{
Byte[] sendByte = new Byte[64];
string sendStr = "服务器端说:" + rtfSendMessage.Text + "\n";
rtfShowMessage.AppendText(" " + sendStr);
sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
acceptedSocket.Send(sendByte, sendByte.Length, 0);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
C# 使用了与请求的协议不兼容的地址 代码如下
答案:2 悬赏:60 手机版
解决时间 2021-04-05 11:40
- 提问者网友:末路
- 2021-04-05 06:32
最佳答案
- 五星知识达人网友:末日狂欢
- 2021-04-05 07:59
在前
全部回答
- 1楼网友:街头电车
- 2021-04-05 09:37
你绑定的ip是ipv6的地址(hostip是ipv6),所以报错,应该绑定ipv4的地址
public string getlocalipv4()
{
ipaddress[] ips = dns.gethostentry(dns.gethostname()).addresslist;
//遍历获得的ip集以得到ipv4地址
foreach (ipaddress ip in ips)
{
//筛选出ipv4地址
if (ip.addressfamily == addressfamily.internetwork)
{
return ip.tostring();
}
}
//如果没有则返回ipv6地址
return ips[0].tostring();
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯