客服端代码 package rediobroadcast;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.util.logging.Level;import java.util.logging.Logger;import javax.swing.JOptionPane;/** * * @author Administrator */public class Broadcast extends javax.swing.JFrame { static Socket skt; //客户端socket static OutputStream os; //客户端输出流 static InputStream is;//客户端输入流 /** Creates new form Broadcast */ public Broadcast() { initComponents(); // 界面 这里的代码是自动生成故此没写 connection_Button.setEnabled(false); this.setTitle("BroudCast window"); BroadcastC.setLineWrap(true);// 显示消息的JTextArea 设置为自动换行 content.setLineWrap(true);//将发送的JTextArea 设置为自动换行 }lass receive extends Thread{receive(){os=skt.getOutputStream();is=skt.getInputStream();}@Override public void run(){ byte[] bt = new byte[100]; int length = 0; while(true){ try { length = is.read(bt); //接受服务端消息 String send = new String(bt, 0, length); if (send.indexOf("@") == 0) { //消息首字母为@ 则为群发消息 BroadcastC.append("广播信息:\n" + send.substring(1, send.length()) + "\n"); } else { BroadcastC.append("服务器信息:\n" + send + "\n"); } } catch (IOException ex) { Logger.getLogger(Broadcast.class.getName()).log(Level.SEVERE, null, ex); } } } } private void connection_Button ActionPerformed(java.awt.event.ActionEvent evt) { try { int port1 = Integer.valueOf(port.getText());//port1 界面输入服务端端口号 //建立客户端socket skt = new Socket(ip.getText(), port1); //ip 界面输入的服务端ip地址 if(skt.isConnected()){ JOptionPane.showMessageDialog(null, "连接服务器成功"); send_Button.setEnabled(true);//设置客户端 发送button 可用 connection_Button.setEnabled(false);//设置 connection-button为不可用 BroadcastC.append("连接服务器成功\n"); //消息提示 } new receive().start(); //新建线程接受服务端信息 } catch (Exception e) { JOptionPane.showMessageDialog(null, "连接服务器失败,请重新连接"); BroadcastC.append("连接服务器失败\n"); } // TODO add your handling code here: } private void send_ButtonPerformed(java.awt.event.ActionEvent evt) { String s = content.getText(); //获取要发送的消息 try { if(s!=null){ os.write(s.getBytes()); //发送消息 BroadcastC.append("我说:\n" + s + "\n"); content.setText(""); s=""; } } catch (Exception e) { }
// TODO add your handling code here: } 服务端代码package chatserver;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Vector;import java.util.logging.Level;import java.util.logging.Logger;/** * * @author Administrator */public class server { static Vector vt=new Vector(); // 用来保存每个客户端的socket static String sendMsg=null;// 群发消息存储 static ServerSocket ss; //服务端serversocket public static void main(String args[]){ try { ss = new ServerSocket(1126); } catch (IOException ex) { Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex); }new serverSocket(ss).start(); //新建启动服务进程 } static void sendall(Socket s){ // 群发方法 s为发送消息的客户端 socket System.out.println("――――――jinru――――――");OutputStream os; for(int i=0;i