记得先运行服务器再打开客户端,可以多人同时聊天,感觉挺好玩的
Server-服务器部分
package com.hp.pro2; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketAddress; import java.util.ArrayList; public class gServer implements Runnable{ private DatagramSocket DS; private int Port = 9998; //服务器与客户所连接的端口号 private ArrayList<SocketAddress> clients = new ArrayList<SocketAddress>(); //保存客户端IP地址 public gServer() throws Exception{ try { DS = new DatagramSocket(Port); new Thread(this).start(); } catch (Exception ex) { } } public void run(){ try{ while(true){ byte[] data = new byte[255]; DatagramPacket DP = new DatagramPacket(data,data.length); DS.receive(DP); SocketAddress clientip = DP.getSocketAddress(); if(!clients.contains(clientip)){ clients.add(clientip); } this.sendAll(DP); } }catch(Exception ex){ } } private void sendAll(DatagramPacket dp) throws Exception { for(SocketAddress sa : clients){ DatagramPacket dd = new DatagramPacket(dp.getData(),dp.getLength(),sa); DS.send(dd); } } public static void main(String[] args) throws Exception{ new gServer(); } }Client-客户端
package com.hp.java; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class GClient extends JFrame implements Runnable,ActionListener { private JTextField field = new JTextField(); private JTextArea area = new JTextArea("聊天内容:\n"); private String name = null; private int Port = 9998; //端口号 private DatagramSocket DS; public GClient(){ this.setTitle("客户端"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(area, BorderLayout.CENTER); this.add(field, BorderLayout.SOUTH); field.addActionListener(this); this.setSize(220, 290); this.setVisible(true); name = JOptionPane.showInputDialog("输入昵称"); try { DS = new DatagramSocket(); InetAddress address = InetAddress.getByName("Localhost"); //服务器所在的电脑IP地址 DS.connect(address,Port); String str = name + "登录!"; byte[] data = str.getBytes(); DatagramPacket DP = new DatagramPacket(data,data.length); DS.send(DP); new Thread(this).start(); } catch (Exception e) { } } public void run(){ try{ while(true){ byte[] data = new byte[255]; DatagramPacket DP = new DatagramPacket(data,data.length); DS.receive(DP); String str = new String(DP.getData(),0,DP.getLength()); area.append(str + '\n'); } }catch(Exception ex){ } } public void actionPerformed(ActionEvent e){ try{ String str = name + "说:" + field.getText(); byte[] dd = str.getBytes(); DatagramPacket Data = new DatagramPacket(dd,dd.length); DS.send(Data); field.setText(""); }catch(Exception ex){ } } public static void main(String[] args){ new GClient(); } }