上一节的当前的服务器只有像客户端发送数据的功能,并没有从客户端读取数据的功能,我们这一节将进行改进:
新建一个ChatManager类:
package com.test.test; import java.util.Vector; public class ChatManager { //完成类的单例: private ChatManager(){} private static final ChatManager cm=new ChatManager(); public static ChatManager getChatManager(){ return cm; } //完成ChatSocket线程的管理: Vector<ChatSocket> vector=new Vector<ChatSocket>(); //为当前的集合添加一个新的ChatSocket对象: public void add(ChatSocket cs){ vector.add(cs); } //某一个线程可以调用下面的函数像其他客户端发送信息 public void publish(ChatSocket cs,String out){ for (int i = 0; i < vector.size(); i++) { ChatSocket csChatSocket=vector.get(i); //判断用于当前发送的线程就不用再接收此条信息了 if(!cs.equals(csChatSocket)){ csChatSocket.out(out); } } } }
修改其他类1:
package com.test.test; public class MyServerSocket { public static void main(String[] args) { new ServerListener().start(); } }
2:
package com.test.test; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JOptionPane; public class ServerListener extends Thread { public void run() { try { ServerSocket serverSocket=new ServerSocket(12345); while(true){ Socket socket=serverSocket.accept(); JOptionPane.showMessageDialog(null,"有客户端连接到了12345端口!"); ChatSocket cs=new ChatSocket(socket); cs.start(); ChatManager.getChatManager().add(cs); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3.
package com.test.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.Socket; public class ChatSocket extends Thread { Socket socket; public ChatSocket(Socket s){ this.socket=s; } public void out(String out){ try { socket.getOutputStream().write(out.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void run() { try { BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); String line=null; while((line=br.readLine())!=null){ ChatManager.getChatManager().publish(this, line); } br.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
类结构如下:
此时我们进行测试,打开三个终端,然后连接,然后输入内容,这样每一个客户端都能收到别人发送的信息:
时间: 2024-10-13 07:17:47