远程IP地址和端口
ip="192.168.7.100"
port=3000;
本地接受端口:
localPort=5000
下面是连接设备代码: public byte[] DeviceComunicationTest(string ip,int Port, byte[] Cmd, int len)
{
udp.Connect(ip, Port);
udp.Send(Cmd, len);
byte[] receive = new byte[256];
return UdpReceiveData(ip, localPort);// 接受设备返回数据
}
接受返回数据: public byte[] UdpReceiveData(string ip,int LocalPort)
{
ipadr = new IPEndPoint(IPAddress.Parse(ip), LocalPort);
return udp.Receive(ref ipadr);// 死在这句上面了
}
接受函数里的IP地址:换成本地的,或远程的IP都不行呢 请教一下,哪里出了问题? 谢谢
但有个问题就是
udp只有连接,没有绑定本地端口
凭什么能接收到数据啊?
private readonly Int32 _RemotePort = 3000;
private readonly String _RemoteIP = "192.168.1.101"; public byte[] DeviceComunicationTest(string ip, int Port, byte[] Cmd, int len)
{
_UDP = new UdpClient(_RemotePort);
_UDP.Connect(_RemoteIP, _RemotePort); _UDP.Send(Cmd, len); byte[] receive = new byte[256];
return UdpReceiveData(ip, _RemotePort);// 接受设备返回数据 } public byte[] UdpReceiveData(string ip, int remotePort)
{
IPEndPoint ipadr = new IPEndPoint(IPAddress.Parse(ip), remotePort);
return _UDP.Receive(ref ipadr);// 死在这句上面了 } private void button1_Click(object sender, EventArgs e)
{
Byte[] bytes = new Byte[2];
bytes[0] = 1;
bytes[1] = 2; Byte[] rBytes = DeviceComunicationTest(_RemoteIP, _RemotePort, bytes, bytes.Length);
MessageBox.Show(rBytes[0] + " " + rBytes[1]);
}
这是MSDN上的例子 //Creates a UdpClient for reading incoming data.
//这里绑定本地端口,你可以改为本地5000
UdpClient receivingUdpClient = new UdpClient(11000); //Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
//这里指定远端机器的ip和端口,如果只是接收不发送的话,可以随便指定
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try{ // Blocks until a message returns on this socket from a remote host.
//接收数据,并返回远程机器的ep
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
}
catch ( Exception e ){
Console.WriteLine(e.ToString());
}
所以,本地接受的端口是:5000
原来声明如下
UdpClient udp = new UdpClient();
用VS2005 时,这么声明,上面的程序使用时也没有问题的 现在改成这样:
UdpClient udp = new UdpClient(5000); 接收是:
public byte[] UdpReceiveData(string ip, int remotePort)
{
IPEndPoint ipadr = new IPEndPoint(IPAddress.Parse(ip),remotePort );
return _UDP.Receive(ref ipadr);// 死在这句上面了 }////
总之,,声明UDP时,,加个本地端口号,就好了 但是奇怪的是,,为什么VS2005时,, 声明时UDP不要 加本地端口号
在接收时,指定端口号可以
用VS2010时,,在接收时,指定端口号就不行呢?
就是这句
byte[] receive = new byte[256];
public int DeviceComunicationTest(string ip,int Port, byte[] Cmd, int len)
{
udp.Bind(new IPEndPoint(IPAddress.Any, 5000));
udp.Connect(ip, Port);
udp.Send(Cmd, len);
return udp.Receive(receive);// 返回数据长度,内容就在receive中。
}