说明:该程序使用了多线程技术,在使用的时候请将发送IP该成广播IP地址,即可实现群聊:
/*
* 群聊主线程
*/
package com.lin.michael;
public class CharMain {
public static void main(String[] args){
//启动接收线程
ChartReceieve chartReceieve = new ChartReceieve();
chartReceieve.start();
//开启发送线程
ChartSender chartSender = new ChartSender();
chartSender.start();
}
}
//发送类
/*
* 群聊发送端
*/
package com.lin.michael;
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;
import java.net.UnknownHostException;
public class ChartSender extends Thread {
@Override
public void run() {
try {
//1.建立udp通信
DatagramSocket socket = new DatagramSocket();
//2.准备数据,把数据放入到数据包中发送
BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
DatagramPacket packet = null;
while((line=keyReader.readLine())!=null){
//把数据封装到数据包中发送出去
packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getLocalHost(),9090);
//把数据发送出去
socket.send(packet);
}
//关闭资源
socket.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//接收类
/*
* 群聊接收端
*/
package com.lin.michael;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class ChartReceieve extends Thread{
@Override
public void run() {
try {
//1.建立udp服务,要监听一个端口;
DatagramSocket socket = new DatagramSocket(9090);
//2.准备数据并使用包来封装
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
//持续接收发送的数据
while(true){
//接收数据包放入到packet中
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress() + "说:" + new String(buf, 0, packet.getLength()));
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}