說明:該程序使用了多線程技術(shù),在使用的時候請將發(fā)送IP該成廣播IP地址类少,即可實現(xiàn)群聊:
/*
* 群聊主線程
*/
package com.lin.michael;
public class CharMain {
public static void main(String[] args){
//啟動接收線程
ChartReceieve chartReceieve = new ChartReceieve();
chartReceieve.start();
//開啟發(fā)送線程
ChartSender chartSender = new ChartSender();
chartSender.start();
}
}
//發(fā)送類
/*
* 群聊發(fā)送端
*/
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.準備數(shù)據(jù),把數(shù)據(jù)放入到數(shù)據(jù)包中發(fā)送
BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
DatagramPacket packet = null;
while((line=keyReader.readLine())!=null){
//把數(shù)據(jù)封裝到數(shù)據(jù)包中發(fā)送出去
packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getLocalHost(),9090);
//把數(shù)據(jù)發(fā)送出去
socket.send(packet);
}
//關(guān)閉資源
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服務(wù)渔扎,要監(jiān)聽一個端口硫狞;
DatagramSocket socket = new DatagramSocket(9090);
//2.準備數(shù)據(jù)并使用包來封裝
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
//持續(xù)接收發(fā)送的數(shù)據(jù)
while(true){
//接收數(shù)據(jù)包放入到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();
}
}
}