服务器代码
- public class UdpServer {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception{
- // TODO Auto-generated method stub
-
- //开启一个线程,监听端口10000的数据包
- Executors.newSingleThreadExecutor().execute(
- new Runnable(){
- public void run(){
- try {
- DatagramSocket ds = new DatagramSocket(10000);
- byte[] buf = new byte[1024];
- int length = 0;
- DatagramPacket dp = new DatagramPacket(buf, 1024);
- while (true) {
- ds.receive(dp);
- System.out.println(dp.getAddress()+"::"+dp.getLength()+":"+new String(dp.getData(), 0, dp.getLength()));
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- });
- //开启一个线程,监听端口10001的数据包
- Executors.newSingleThreadExecutor().execute(
- new Runnable(){
- public void run(){
- try {
- DatagramSocket ds = new DatagramSocket(10001);
- byte[] buf = new byte[1024];
- int length = 0;
- DatagramPacket dp = new DatagramPacket(buf, 1024);
- while (true) {
- ds.receive(dp);
- System.out.println(dp.getAddress()+"::"+dp.getLength()+":"+new String(dp.getData(), 0, dp.getLength()));
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- });
- }
- }
复制代码
客户端代码
- public class UdpClient {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- //开启一个线程,向本机的10000端口发送数据包
- Executors.newSingleThreadExecutor().execute(
- new Runnable(){
- public void run(){
- try {
- DatagramSocket ds = new DatagramSocket();
- byte[] buf = "THIS IS NO.1".getBytes();
- InetAddress ia = InetAddress.getLocalHost();
- DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 10000);
- while (true) {
- ds.send(dp);
- try {
- Thread.sleep(1000);
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- });
- //开启一个线程,向本机的10001端口发送数据包
- Executors.newSingleThreadExecutor().execute(
- new Runnable(){
- public void run(){
- try {
- DatagramSocket ds = new DatagramSocket();
- byte[] buf = "this is No.2".getBytes();
- InetAddress ia = InetAddress.getLocalHost();
- DatagramPacket dp = new DatagramPacket(buf, buf.length, ia, 10001);
- while (true) {
- ds.send(dp);
- try {
- Thread.sleep(1000);
- } catch (Exception e) {
- // TODO: handle exception
- }
- }
- } catch (Exception e) {
- // TODO: handle exception
- e.printStackTrace();
- }
- }
- });
- }
- }
复制代码 功能:客户端想服务端的不同端口发送请求
|