public SendRunnable(String destHost, int port, DatagramSocket ds) {
this.destHost = destHost;
this.port = port;
this.ds = ds;
}
@Override
public void run() {
while(true){
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(Thread.currentThread().getName()+":");
String say;
DatagramPacket dp=null;
try {
say=br.readLine();
dp=new DatagramPacket(say.getBytes(),say.getBytes().length ,InetAddress.getByName(destHost), port);
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
信息接收线程类:
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/接收线程类
/
public class ReceiveRunnable implements Runnable {
private DatagramSocket ds;
public ReceiveRunnable(DatagramSocket ds) {
this.ds = ds;
}
@Override
public void run() {
while (true) {
byte[] b = new byte[1024];
DatagramPacket dp = new DatagramPacket(b, b.length);
try {
ds.receive(dp);// 接收之前一直阻塞
String ip = dp.getAddress().getHostName();// 获取发送方的IP
int post = dp.getPort();// 获取发送方的端口号
System.out.println(ip + ":" + post + "说:"
+ new String(dp.getData(), 0, dp.getLength()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
聊天端口一:
package udp;
import java.net.DatagramSocket;
import java.net.SocketException;
class Chat1 {
public static void main(String[] args) throws SocketException {
DatagramSocket ds=new DatagramSocket(9999);
new Thread(new ReceiveRunnable(ds)).start();
new Thread(new SendRunnable("localhost", 8888, ds),"白雪公主").start();
}
}
聊天端口二:
package udp;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Chat2 {
public static void main(String[] args) throws SocketException {
DatagramSocket ds=new DatagramSocket(8888);
new Thread(new ReceiveRunnable(ds)).start();
new Thread(new SendRunnable("localhost", 9999, ds),"青蛙王子").start();
}
}
运行结果
白雪公主:127.0.0.1:8888说:你好,公主
你好,王子
白雪公主:127.0.0.1:8888说:你在干什摸,公主
我在和你聊天
白雪公主:
:
青蛙王子:你好,公主
青蛙王子:127.0.0.1:9999说:你好,王子
你在干什摸,公主
青蛙王子:127.0.0.1:9999说:我在和你聊天
原文地址:http://blog.51cto.com/13501268/2104142