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 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.15.255"), 9090); //把数据发送出去 socket.send(packet); } //关闭 资源 socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; //群聊接收端 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; while(flag){ socket.receive(packet); // packet.getAddress() 获取对方数据 包的IP地址对象。 System.out.println(packet.getAddress().getHostAddress()+"说:"+new String(buf,0,packet.getLength())); } //关闭资源 socket.close(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class ChatMain { public static void main(String[] args) { ChatReceive chatReceive = new ChatReceive(); chatReceive.start(); ChatSender chatSender = new ChatSender(); chatSender.start(); } }