代码演示如下:
客户端:
public class Client { public static void main(String[] args) throws Exception{ System.out.println("客户端开启!"); //1.创建Socket对象,并同时请求与服务端程序的连接。 Socket socket = new Socket("127.0.0.1",8888); //创建一个独立的线程,负责随时从socket中接收服务端发送过来的消息 new ClientReaderThread(socket).start(); //2.从socket通信管道中得到一个字节输出流。用来发数据给服务端程序 OutputStream os = socket.getOutputStream(); //3.把低级的字节输出流包装成数据输出流 DataOutputStream dos = new DataOutputStream(os); Scanner sc = new Scanner(System.in); while (true) { System.out.println("请输入:"); String msg = sc.nextLine(); //一旦用户输入了exit,就退出客户端程序 if ("exit".equals(msg)){ System.out.println("退出成功!"); dos.close(); socket.close(); break; } //4.开始写数据出去了 dos.writeUTF(msg); dos.flush(); } } }
服务端:
public class Server { public static List<Socket> onLineSockets = new ArrayList<>(); public static void main(String[] args) throws Exception{ System.out.println("服务端开启!"); //1.创建ServerSocket的对象,同时为服务端注册端口。 ServerSocket serverSocket = new ServerSocket(8888); while (true) { //2.使用serverSocket对象,调用一个accept方法,等待客户端的连接请求 Socket socket = serverSocket.accept(); onLineSockets.add(socket); System.out.println("有人上线了:" + socket.getRemoteSocketAddress()); //3.把这个客户端对应的socket通信管道,交给一个对立的线程负责处理 new ServerReaderThread(socket).start(); } } }
客户端线程类:
public class ClientReaderThread extends Thread{ private Socket socket; public ClientReaderThread(Socket socket){ this.socket = socket; } @Override public void run(){ try { InputStream is = socket.getInputStream(); DataInputStream dis = new DataInputStream(is); while (true) { try { String msg = dis.readUTF(); System.out.println(msg); } catch (Exception e) { dis.close(); socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); } } }
服务端线程类:
public class ServerReaderThread extends Thread{ private Socket socket; public ServerReaderThread(Socket socket){ this.socket = socket; } @Override public void run(){ try { InputStream is = socket.getInputStream(); DataInputStream dis = new DataInputStream(is); while (true) { try { String msg = dis.readUTF(); System.out.println(msg); //把这个消息分发给客户端进行接收 sendMsgToALL(msg); } catch (Exception e) { System.out.println("有人下线了:"+ socket.getRemoteSocketAddress()); dis.close(); socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); } } private void sendMsgToALL(String msg) throws Exception { // 发送给全部在线的socket管道接收 for (Socket onLineSocket : Server.onLineSockets) { OutputStream os = onLineSocket.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF(msg); dos.flush(); } } }