package com.fz.song; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * 学习Java网络知识 */ //这是一个服务端 // public class Server { public static void main(String[] args) throws IOException { //获取一个服务ServerSocket对象 //new 一个服务器端的ServerSocket ServerSocket serverSocket = new ServerSocket(8888); //调用accept来接受请求 Socket socket = serverSocket.accept(); //获取ip地址 String hostAddress = socket.getInetAddress().getHostAddress(); System.out.println(hostAddress + ":链接成功"); //从Socket获取输入流 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); String line = ""; while ((line = br.readLine()) != null) { System.out.println("line = " + line); if (line.equals("over")) { break; } else { // bw.write(line.toUpperCase()); // bw.newLine(); // bw.flush(); pw.println(line.toUpperCase()); } } System.out.println(hostAddress + ":关闭链接"); br.close(); pw.close(); //bw.close(); socket.close(); } }
package com.fz.song; import java.io.*; import java.net.Socket; /** * 这是一个客户端 */ public class Client { public static void main(String[] args) throws IOException { //创建一个客户端的Socket Socket socket = new Socket("127.0.0.1", 8888); //获取键盘输入流 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); PrintWriter pw=new PrintWriter(socket.getOutputStream(),true); BufferedReader br2=new BufferedReader(new InputStreamReader(socket.getInputStream())); while (true) { String line = br.readLine(); // bw.write(line); // bw.newLine(); // bw.flush(); pw.println(line); if (line.equals("over")) { break; } else { String str = br2.readLine(); System.out.println("返回值 = " + str); } } br.close(); //bw.close(); br2.close(); socket.close(); } }