服务器端: package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class SeverTest { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocket server = new ServerSocket(8888); Socket socket = server.accept(); InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr, 100); String b = null; while ((b = br.readLine()) != null) { System.out.println("我是服务器,请讲:" + b); } socket.shutdownInput();// 关闭输入流 OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); Scanner scanner = new Scanner(System.in); String s = ""; while (!(s = scanner.nextLine()).equals("")) { pw.write(s); } pw.flush(); pw.close(); os.close(); scanner.close(); br.close(); isr.close(); is.close(); socket.close(); server.close(); } } 客户端: package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class ClientTest { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 8888); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os); Scanner scanner = new Scanner(System.in); String s = ""; while (!(s = scanner.nextLine()).equals("")) { pw.write(s); } // pw.write("这里是客户端,我可以告诉你用户名和密码吗?"); pw.flush(); socket.shutdownOutput();// 关闭输出流 InputStream is = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr, 100); String b = null; while ((b = br.readLine()) != null) { System.out.println(b); } scanner.close(); br.close(); isr.close(); is.close(); pw.flush(); pw.close(); os.close(); socket.close(); } }
注意:
①在服务器端建立输入流,获取完输入流之后一定要把输入流关闭,否则无法进行后面的输出流操作。
②在客户端建立输出流,发送输出流之后一定要把输出流关闭,否则无法进入后面的输入流操作。