003socket 基本使用

    技术2022-07-10  156

    package sock; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class MySock3 { public static void main(String[] args) throws Exception { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));//这个是之前使用的。io Socket socket = new Socket("127.0.0.1", 12313); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream())); String line = null; String s; while ((line = bufferedReader.readLine()) != null) { if ("end".equals(line)) { break; } bufferedWriter.write(line); bufferedWriter.newLine(); bufferedWriter.flush(); s = bufferedReader1.readLine(); System.out.println("收到"+s); } // while () } } class MySer3{ public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(12313); Socket socket = serverSocket.accept(); BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream())); // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//替换 PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true); String line =null; while ((line = bufferedReader1.readLine()) != null) { System.out.println("line = " + line); // bufferedWriter.write(line.toUpperCase()); // bufferedWriter.newLine(); // bufferedWriter.flush(); printWriter.println(line); } socket.close();//会有个结束标记。 客户端的read也会自动暂停了。 serverSocket.close(); } }

    可以利用不同的io操作。

    Processed: 0.027, SQL: 9