一个 Java 的 Socket 服务器和客户端通信的例子
http://blog.csdn.net/defonds/article/details/7971259
多个客户端对应一个服务端的通信的一个小例子。
服务端和客户端代码:
public class Server { /** * 监听的端口 */ public static final int PORT = 12345; public static void main(String[] args) { System.out.println("服务器启动》》》》》》"); Server server = new Server(); server.init(); } public void init(){ try { ServerSocket serverSocket = new ServerSocket(PORT); while (true){ //一旦有堵塞,表示服务器与客户端获得了连接 Socket client = serverSocket.accept(); new HandlerThread(client); } } catch (Exception e) { e.printStackTrace(); } } private class HandlerThread implements Runnable{ private Socket socket; public HandlerThread(Socket socket) { this.socket = socket; new Thread(this).start(); } @Override public void run() { try { //读取客户端数据 DataInputStream input = new DataInputStream(socket.getInputStream()); //这里要注意和客户端输出流的写方法对应,否则会抛 EOFException String clientInputStr = input.readUTF(); //处理客户端发送的数据 System.out.println("客户端发过来的内容:"+clientInputStr); //想客户端发送消息 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.println("请输入:\t"); String outStr = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(outStr); out.close(); input.close(); } catch (IOException e) { System.out.println("服务器异常:"+e.getMessage()); }finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System.out.println("服务端 finally 异常:" + e.getMessage()); } } } } } }
public class Client { public static final int PORT = 12345; public static final String IP_ADDR = "localhost"; public static void main(String[] args) { System.out.println("客户端启用》》》》》》"); System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n"); while (true){ Socket socket = null; try { //创建一个流套接字并将其连接到指定主机上的指定端口号 socket = new Socket(IP_ADDR,PORT); socket.setSoTimeout(5000); //读取服务器端数据 DataInputStream input = new DataInputStream(socket.getInputStream()); //向服务器端发送数据 DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("请输入: \t"); String str = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(str); String ret = input.readUTF(); System.out.println("服务器端返回过来的是: " + ret); if (ret.endsWith("OK")) { System.out.println("客户端将关闭连接"); Thread.sleep(500); break; } out.close(); input.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); }finally { if (socket != null) { try { socket.close(); } catch (IOException e) { socket = null; System.out.println("客户端 finally 异常:" + e.getMessage()); } } } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· C# 模式匹配全解:原理、用法与易错点
· 记一次SSD性能瓶颈排查之路——寿命与性能之间的取舍
· 理解 .NET 结构体字段的内存布局
· .NET 9中的异常处理性能提升分析:为什么过去慢,未来快
· 字符集、编码的前世今生
· C# 模式匹配全解:原理、用法与易错点
· 杂七杂八系列----C#代码如何影响CPU缓存速度?
· C#/.NET/.NET Core优秀项目和框架2025年5月简报
· 鸿蒙仓颉语言开发实战教程:商城应用个人中心页面
· FFmpeg开发笔记(六十三)FFmpeg使用vvenc把视频转为H.266编码