客户端
package TestSocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class SocketClient { public static String readLine = "hello"; //1.建立一个socket //2.连接 //3.发送数据 //4.获取数据 @SuppressWarnings("resource") public static void main(String[] args) throws Exception, Exception { Socket socket = new Socket("localhost",8899); BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in)); BufferedReader socketIn = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter socketOut = new PrintWriter(socket.getOutputStream()); while (readLine != "bye") { System.out.print("Client:"); readLine = systemIn.readLine(); socketOut.println(readLine); socketOut.flush(); String inTempString = socketIn.readLine(); System.out.println(inTempString); System.out.println("Server"); } } }
服务端
package TestSocket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.util.Scanner; public class SocketServer { public static String readLine = "hello"; public static void main(String[] args) throws Exception { //创建server服务器绑定端口号 ServerSocket server = new ServerSocket(8899); // 调用accept镜像阻塞,当有申请连接时会打开阻塞并返回socket System.out.println("hello"); Socket accept = server.accept(); //获取服务器输入 inputStreamReader是字节流转换成字符流 BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in)); BufferedReader sockerIn = new BufferedReader(new InputStreamReader(accept.getInputStream())); //printwriter具有自动行刷新的缓冲字符输出流,特点是可以按行写出字符串,并且可以自动行刷新。 PrintWriter socketOut = new PrintWriter(accept.getOutputStream()); while (readLine != "bye") { String inTempString = sockerIn.readLine(); System.out.print("Client:"); System.out.println(inTempString); System.out.println("Server"); readLine = systemIn.readLine(); socketOut.println(readLine); socketOut.flush(); } } }
原文:https://www.cnblogs.com/BookMiki/p/14083091.html