多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 1.编辑线程类 ~~~ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; public class ServerThread extends Thread{ private Socket socket; public ServerThread(Socket socket){ this.socket=socket; } @Override public void run() { // 从socket中获取字节输入流对象 try (InputStream inputStream = socket.getInputStream()) { //把字节输入流包装成缓存字节输入流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String msg; while ((msg=bufferedReader.readLine())!=null){ System.out.println("服务器收到信息:"+msg); } } catch (Exception e) { e.printStackTrace(); } } } ~~~ # 2.编写Server类 ~~~ import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { System.out.println("服务端启动"); try { // ServerSocket 对象进行服务器端口注册 ServerSocket serverSocket = new ServerSocket(9999); while (true){ new ServerThread(serverSocket.accept()).start(); } }catch (Exception e){ e.fillInStackTrace(); } } } ~~~ 3.客户端 ~~~ import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class Client { public static void main(String[] args) { try { // 创建socket链接请求 Socket socket = new Socket("127.0.0.1", 9999); // 从socket中获取字节输出流对象 OutputStream socketOutputStream = socket.getOutputStream(); //把字节输出流包装成打印流 PrintStream printStream = new PrintStream(socketOutputStream); // 扫描器 Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请说:"); printStream.println(scanner.nextLine()); printStream.flush(); } } catch (Exception e) { e.fillInStackTrace(); } } } ~~~ BIO是一个连接一个线程。