Java网络编程 TCP网络通信编程字符流 meowrain 收录于 网络编程2024-05-23 约 300 字 预计阅读 1 分钟 目录 TCP字符流编程 代码 警告 本文最后更新于 2024-05-23,文中内容可能已过时。 TCP字符流编程 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package org.example.socket; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class SocketTcp03Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); Socket socket = serverSocket.accept(); System.out.println("服务端启动,正在监听9999端口"); InputStream inputStream = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(reader); String s = bufferedReader.readLine(); System.out.println(s); socket.shutdownInput(); OutputStream outputStream = socket.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(outputStream); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("hello,client字符流"); bufferedWriter.newLine(); bufferedWriter.flush(); socket.shutdownOutput(); //关闭外层流即可 bufferedReader.close(); bufferedWriter.close(); serverSocket.close(); socket.close(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package org.example.socket; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class SocketTcp03Client { public static void main(String[] args) throws IOException { Socket socket = new Socket(InetAddress.getLocalHost(),9999); System.out.println("客户端启动,准备向9999端口发送信息"); OutputStream outputStream = socket.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(outputStream); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("hello,server字符流"); bufferedWriter.newLine(); //写用newLIne方法,read也要用readLine方法 bufferedWriter.flush(); //需要刷新 socket.shutdownOutput(); InputStream inputStream = socket.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(reader); String s = bufferedReader.readLine(); System.out.println(s); socket.close(); bufferedWriter.close(); bufferedReader.close(); } } 相关内容 Java网络编程 TCP网络通信编程字节流 Go网络编程 JDBC_韩顺平老师转载 Java面向对象基础(高级) Java面向对象基础(中级)