import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
* UDP实现无界面聊天室*
*/
public class UDPEnd1 {
public static void main(String[] args) {
new Thread(new Sender()).start();
new Thread(new Receiver()).start();
}
}
//发送端线程
class Sender implements Runnable{
@Override
public void run() {
try {
//建立Socket,无需指定端口
DatagramSocket ds=new DatagramSocket();
//通过控制台标准输入
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
String line=null;
DatagramPacket dp=null;
//do-while结构,发送为exit时,退出
do{
line=br.readLine();
byte[] buf=line.getBytes();
//指定为广播ip
dp=new DatagramPacket(buf, buf.length,
InetAddress.getByName("192.168.1.255"),9090);
ds.send(dp);
}while(!line.equals("exit"));
ds.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//接收端线程
class Receiver implements Runnable{
@Override
public void run() {
try {
//接收端需指定端口
DatagramSocket ds=new DatagramSocket(9090);
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf, buf.length);
String line=null;
//当收到消息为exit时,退出
do{
ds.receive(dp);
line=new String(buf,0,dp.getLength());
System.out.println(line);
}while(!line.equals("exit"));
ds.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
UDP聊天小程序-菜鸟
最新推荐文章于 2024-07-17 15:49:27 发布