请求的地址在其上下文中无效 [英] the requested address is not valid in its context
问题描述
我使用以下代码:
给表单对象命名,如下所示:
您的IP文本框名称= textLocalIp,
您的端口文本框名称= textLocalPort,
朋友的IP文本框名称= textFriendsIp
朋友的端口文本框名称= textFriendsPort
列表框消息名称= listMessage,
消息发送名称的文本框= textMessage,
开始按钮名称= buttonStart,
发送按钮名称= buttonSend
步骤3:向项目添加2个名称空间.
使用
使用 System.Net.Sockets;
//设置套接字
sck = 新&nSocket( AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true );
//获得自己的IP
textLocalIp.Text = GetLocalIP();
textFriendsIp.Text = GetLocalIP();
然后添加方法GetLocalIP(),如下所示.此方法会将本地IP地址返回到文本框.
//返回您自己的IP
私有 {
IPHostEntry主机;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IP地址ip 在 host.AddressList中)
{
{
  ; 返回 ip.ToString();
}
}
返回 "127.0.0.1" ;
}
尝试
{ epLocal =< 新 IPEndPoint(IPAddress.Parse(textLocalIp.Text), 转换 .ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
//连接到远程IP和端口
epRemote = 新&IPEndPoint( IPAddress.Parse(textFriendsIp.Text),转换 .ToInt32(textFriendsPort.Text));
sck.Connect(epRemote);
//开始收听特定端口 >
buffer = 新 字节 [1500];
sck. BeginReceiveFrom(buffer,0,buffer.Length,SocketFlags.None, ref epRemote, new
AsyncCallback ),缓冲区);
//释放按钮以发送消息
buttonSend.Enabled = true ;
buttonStart.Text = 已连接" ;
buttonStart.Enabled = false ;
textMessage.Focus();
}
渔获 ( {
MessageBox.Show(ex.ToString());
}
现在,您需要添加一个回调函数MessageCallBack.只需添加以下代码.
尝试
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
//检查是否存在实际信息,如果(size> 0){//用于帮助我们获取数据
字节 [] receiveData = byte [1464];
//获取消息数据
receiveData =(字节 [])aResult.AsyncState;
//将消息数据字节数组转换为字符串
ASCIIEncoding eEncoding = 新 ASCIIEncoding();
字符串 receivedMessage = eEncoding.GetString(receivedData);
//将消息添加到列表框
listMessage.Items.Add("朋友:" + receiveMessage);
}
//开始再次监听套接字
缓冲区= 新 byte [1500]; >
sck.BeginReceiveFrom(buffer,0,buffer.Length,SocketFlags.None,参考 epnRemote,新 AsyncCallback(MessageCallBack), 缓冲区);
}
渔获 (异常exp)
{
MessageBox.Show(exp.ToString());
}
尝试
{ //从字符串转换为字节[]
System.Text. ASCII编码 enc = 新 System.Text. ASCIIEncoding ();
byte [] msg = 新 byte [1500]; 跨度>
msg = enc.GetBytes(textMessage.Text);
//发送消息
sck.Send(msg);
//添加到列表框
listMessage.Items.Add("您:" + textMessage.Text);
//清除txtMessage
textMessage.Clear();
}
捕获 (异常 ex)
{
MessageBox.Show(ex.ToString());
}
IP和端口无效
要通过TCP/IP进行通信,您必须指定端口号.该端口必须可用,因此通常是动态的.要获得可用的端口,您应该尝试打开一个套接字并将端口指定为0(至少在使用TcpListener时). 这将导致运行时查找可用端口.您似乎没有这样做,因此得到了错误.听起来您应该获得此端口号,然后在UI中显示它,以便好友"显示在屏幕上.可以连接到同一端口. 请注意,在您的代码中,每个客户端都在打开自己的套接字,因此您使用的端口将不同于其他客户端.因此,您必须计算自己的端口,然后手动输入另一个客户端的远程IP和端口(反之亦然).
通常动态端口在30K边界之上,但是如果您让系统选择一个端口,则它将返回有效端口.
迈克尔·泰勒
http://www.michaeltaylorp3.net
i use follwing code:
Step 1: First make a project, go to Microsoft Visual C# then create a project.
Step 2: Design the Chat Application form with TextBox, label, button and group boxes.
Give the form objects names as in the following:
Your IP textbox name = textLocalIp,
Your Port textbox name = textLocalPort,
Friend's IP textbox name = textFriendsIp
Friend's Port textbox name = textFriendsPort
Listbox Message name = listMessage,
Textbox for Message sending name = textMessage,
Start Button name = buttonStart,
Send Button name = buttonSend
Step 3: Add 2 namespaces to the project.
using System.Net;
using System.Net.Sockets;
Step 4 : Add the following code for the form load, double-click on the form then write the following code.
// set up socket
sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// get own IP
textLocalIp.Text = GetLocalIP();
textFriendsIp.Text = GetLocalIP();
Then add a method GetLocalIP() as follows. This method will return the Local IP address to the text boxes.
// Return your own IP
private string GetLocalIP()
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "127.0.0.1";
}
Step 5: Add the following code under the Start Button click event.
try
{ // binding socket
epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(epLocal);
// connect to remote IP and port
epRemote = new IPEndPoint(IPAddress.Parse(textFriendsIp.Text), Convert.ToInt32(textFriendsPort.Text));
sck.Connect(epRemote);
// starts to listen to an specific port
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new
AsyncCallback(MessageCallBack), buffer);
// release button to send message
buttonSend.Enabled = true;
buttonStart.Text = "Connected";
buttonStart.Enabled = false;
textMessage.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Now, you need to add a callback function MessageCallBack. Just add the following code.
try
{
int size = sck.EndReceiveFrom(aResult, ref epRemote);
// check if theres actually information if (size > 0) { // used to help us on getting the data
byte[] receivedData = new byte[1464];
// getting the message data
receivedData = (byte[])aResult.AsyncState;
// converts message data byte array to string
ASCIIEncoding eEncoding = new ASCIIEncoding();
string receivedMessage = eEncoding.GetString(receivedData);
// adding Message to the listbox
listMessage.Items.Add("Friend: " + receivedMessage);
}
// starts to listen the socket again
buffer = new byte[1500];
sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, newAsyncCallback(MessageCallBack), buffer);
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
Step 6: In this step you need to add the following code for the send button click event.
try
{ // converts from string to byte[]
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] msg = new byte[1500];
msg = enc.GetBytes(textMessage.Text);
// sending the message
sck.Send(msg);
// add to listbox
listMessage.Items.Add("You: " + textMessage.Text);
// clear txtMessage
textMessage.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
IP and port is not valid
To communicate over TCP/IP you have to specify a port number. The port must be available and therefore is generally dynamic. To get a port that is available you should attempt to open a socket and specify a port of 0 (at least when using the TcpListener). This will cause the runtime to find an available port. You don't seem to be doing that and therefore getting the error. It sounds like you should be getting this port # and then displaying it in the UI so the "friend" can connect to the same port. Note that in your code each client is opening their own socket so the port you use will be different than the other clients. So you'll have to calculate your own port and then manually enter the remote IP and port of the other client (and vice versa).
In general dynamic ports are above the 30K boundary but if you are having the system pick one then it'll return a valid port.
Michael Taylor
http://www.michaeltaylorp3.net
这篇关于请求的地址在其上下文中无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!