群聊开始窗口
package com.cn.udp;
/**
* 群聊开始窗口
* @author zhiyong
*
*/
public class ChatMain {
public static void main(String[] args) {
ChatReceive chatReceive = new ChatReceive();
chatReceive.start();
ChatSender chatSender = new ChatSender();
chatSender.start();
}
}
群聊的接收端
package com.cn.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* 群聊的接收端
* @author zhiyong
*
*/
public class ChatReceive extends Thread{
@Override
public void run() {
try {
//建立udp的服务,要监听一个端口
DatagramSocket socket = new DatagramSocket(9090);
//准备空的数据包存储数据
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
boolean flag = true;//标记1
while(flag){
socket.receive(packet);
//packet.getAddress()获取对方数据包的IP地址对象
System.out.println(packet.getAddress().getHostAddress() + "说:" + new String(buf, 0, packet.getLength()));
}
//关闭资源
socket.close();//若在标记1处,不定义一个标志,这句话没有意义,会报错
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
群聊的发送端
package com.cn.udp;
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;
/**
* 群聊的发送端
* @author zhiyong
*
*/
public class ChatSender extends Thread{
@Override
public void run() {
try {
//建立udp服务
DatagramSocket socket = new DatagramSocket();
//准备数据,把数据封装到数据包中发送
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.getByName("192.168.18.255"), 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();
}
}
}