发送端
package com.sxt;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/**
* 客户发
*
* @author Administrator
*
*/
public class UClient {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket(4444, InetAddress.getLocalHost());
new Thread(new Runnable() { //内部类启动多线程,不停地接收包
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
byte b[] = new byte[1024];
ds.receive(new DatagramPacket(b, b.length));
System.out.println(new String(b));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
while (true) {
String s = sc.next();
ds.send(new DatagramPacket(("客户端:"+s).getBytes(), ("客户端:"+s).getBytes().length, InetAddress.getByName("192.168.1.116"), 5555));
}
}
}
接收端
package com.sxt;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
/**
* 咨询师
*
* @author Administrator
*
*/
public class UServer {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket(5555, InetAddress.getLocalHost());
new Thread(new Runnable() { //内部类启动多线程
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
byte b[] = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
ds.receive(dp);
System.out.println(dp.getAddress().getHostAddress()+":"+new String(b));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
while (true) {
String s = sc.next();
ds.send(new DatagramPacket(("服务器:"+s).getBytes(), ("服务器:"+s).getBytes().length, InetAddress.getLocalHost(), 4444));
}
}
}