private void btnStart_Click(object sender, EventArgs e)
{
try
{
epLocal = new IPEndPoint(IPAddress.Parse(txtIP1.Text), Convert.ToInt32(txtPort1.Text));
sck.Bind(epLocal);
epRemote = new IPEndPoint(IPAddress.Parse(txtIP2.Text), Convert.ToInt32(txtPort2.Text));
//Here Error Occures I dont know what is my mistake?
sck.Bind(epRemote);
byte[] buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
btnStart.Text = "Connected";
btnStart.Enabled = false;
btnSend.Enabled = true;
txtMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:3)
您将相同的套接字绑定到多个Endpoint对象,这就是您获得InvalidArgument异常的原因,您可以一次将一个套接字绑定到一个IPEndPoint对象。
当您尝试收听公共IP地址和本地IP时,请尝试使用此
IPEndPoint ep = new IPEndPoint(IPAddress.Any, yourportnumber );
sck.Bind(ep) ;
这将创建一个监听PC的所有IP地址的监听器, 否则,最好使用Seperate套接字对象
如果我是你,我不会从IPAddress
解析本地textbox
,而是使用类似IPAddress.Loopback