110,571
社区成员
发帖
与我相关
我的任务
分享
远程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);// 死在这句上面了
}
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中。
}
UdpClient udp = new UdpClient();
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);// 死在这句上面了
}
//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());
}
private UdpClient _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]);
}