1、服务器类:
package com.serversocket; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Server_02 { //定义保存所有Socket的ArrayList,并将其包装为线程安全的 public static List<Socket> socketList = Collections.synchronizedList(new ArrayList<>()); public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(30000); while(true){ //此行代码会阻塞,会一直等待别人的链接 Socket s = ss.accept(); socketList.add(s); //每当客户端连接成功后启动一个ServerThread线程为该客户端服务 new Thread(new ServerThread02(s)).start(); } } }
2、服务器线程类
package com.serversocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class ServerThread02 implements Runnable { //定义当前线程处理的Socket Socket s = null; //该线程所处理的Socket的输入流 BufferedReader br = null; public ServerThread02(Socket s) throws IOException { this.s = s; //初始化该Socket所对应的输入流 br = new BufferedReader(new InputStreamReader(s.getInputStream())); } public void run() { try { String content = null; //采用循环不断的从Socket中读取客户端发送过来的数据 while ((content = readFromClient()) != null) { //遍历socketList中的每个Socket //将读到的内容向每个Socket发送一次 for (Socket s : Server_02.socketList) { PrintStream ps = new PrintStream(s.getOutputStream()); ps.println(content); } } } catch (IOException e) { e.printStackTrace(); } } //定义读取客户端数据的方法 private String readFromClient() { try { return br.readLine(); //如果捕获到异常,则表明Socket对应的客户端已经关闭 } catch (IOException e) { //删除该Socket Server_02.socketList.remove(s); } return null; } }
3、客户端类
package com.socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class Client_02 { public static void main(String[] args) throws Exception { Socket s = new Socket("127.0.0.1",30000); //客户端启动ClientThread02不断的读取来自服务器的数据 new Thread(new ClientThread02(s)).start(); PrintStream ps = new PrintStream(s.getOutputStream()); String line = null; System.out.println("请输入消息:"); //不断读取键盘的输入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while((line = br.readLine())!=null){ //将用户的键盘输入内容写入Socket对应的输出流 ps.println(line); } } }
4、客户端线程类
package com.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class ClientThread02 implements Runnable { //该线程负责处理的Socket private Socket s = null; //该线程处理的Socket对应的输入流 BufferedReader br = null; public ClientThread02(Socket s) throws IOException{ this.s = s; br = new BufferedReader(new InputStreamReader(s.getInputStream())); } @Override public void run() { try{ String content = null; //不断读取Socket输入流中的内容,并将这些内容打印输出 while((content=br.readLine()) != null){ System.out.println(content); } }catch(IOException e){ e.printStackTrace(); } } }
编写好上面代码之后,首先启动服务器类,然后再启动客户端类(可以启动多个客户端类)
时间: 2024-07-29 06:02:19