真是水平有限,照着写了点。。。惭愧。。。
UdpClient.java
package com.cstp.net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClient {//client
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String s = "河北金融学院";
//数据包(包数据,包数据长度,目的地址,目的地端口号)
DatagramPacket dp=new DatagramPacket(s.getBytes(), s.getBytes().length,
InetAddress.getByName("192.168.1.104"), 3000);
//发送
ds.send(dp);
ds.close();
}
}
UdpServer.java
package com.cstp.net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServer {//server
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf=new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,1024);//这里的数字可以换别的,但不能超过buf.length
// 阻塞式,没收到数据,就一直等着。执行该方法dp里就有了发来的数据
ds.receive(dp);
//取出数据,按数据长度,而非全部,因为可能没有1024个字节,没必要全取
String s = new String(dp.getData(),0,dp.getLength());
System.out.println("收到信息:"+s+"/t from /t"+dp.getAddress().getHostAddress()+"/t 端口:"+dp.getPort());
ds.close();
}
}