JAVA网络编程样例
2022/4/13 20:12:50
本文主要是介绍JAVA网络编程样例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
这篇文章主要用来总结Java在网络编程中的知识点
下面是一个Java客户端与服务端通信的样例程序
//Server public class Server { public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(6666); System.out.println("Server start listening..."); for (; ; ) { Socket sock = ss.accept(); System.out.println("Receviced package from " + sock.getRemoteSocketAddress()); Thread t = new Handler(sock); t.start(); } } } class Handler extends Thread { Socket sock; public Handler(Socket sock) { this.sock = sock; } @Override public void run() { try (InputStream input = this.sock.getInputStream()) { try (OutputStream output = this.sock.getOutputStream()) { handle(input, output); } } catch (Exception e) { try { this.sock.close(); } catch (IOException ioe) { } System.out.println("Client disconnected."); } } private void handle(InputStream input, OutputStream output) throws IOException { var writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8)); var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); writer.write("hello\n"); writer.flush(); for (; ; ) { String s = reader.readLine(); if (s.equals("bye")) { writer.write("bye\n"); writer.flush(); break; } writer.write("ok: " + s + "\n"); writer.flush(); } } }
//client public class client { public static void main(String[] args) throws IOException { Socket sock = new Socket("localhost", 6666); try (InputStream input = sock.getInputStream()){ try(OutputStream output = sock.getOutputStream()){ handle(input, output); } } } private static void handle(InputStream input, OutputStream output) throws IOException{ var writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8)); var reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)); Scanner scanner = new Scanner(System.in); System.out.println("[server]: "+ reader.readLine()); for(;;){ System.out.print(">>>"); String s = scanner.nextLine(); writer.write(s); writer.newLine(); writer.flush(); String resp = reader.readLine(); System.out.println("<<<" + resp); if(resp.equals("bye")) break; } } }
实现功能为服务端与客户端相互通信,收到bye
信号后断开连接,如图所示
这篇关于JAVA网络编程样例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?