💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 1.服务端 ~~~ 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); // 监听socket链接请求 Socket socket = serverSocket.accept(); // 从socket中获取字节输入流对象 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.fillInStackTrace(); } } } ~~~ # 2.客户端 ~~~ import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class Client { public static void main(String[] args) { try { // 创建socket链接请求 final Socket socket = new Socket("127.0.0.1",9999); // 从socket中获取字节输出流对象 final OutputStream socketOutputStream = socket.getOutputStream(); //把字节输出流包装成打印流 final PrintStream printStream = new PrintStream(socketOutputStream); printStream.print("hello word,服务器"); printStream.flush(); }catch (Exception e){ e.fillInStackTrace(); } } } ~~~