上一節實現了客戶端像服務器端發送請求,本節將實現服務器端向客戶端回傳信息,實現原理很簡單,在原來的基礎上,在服務器端實現輸出流,在客戶端實現輸入流即可,具體代碼如下:
服務器端:
package com.socket.demo; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try{ ServerSocket serverSocket=new ServerSocket(8888); System.out.println("----------------服務端運行,開始監聽請求----------------"); Socket socket=serverSocket.accept();//開始監聽 InputStream inputStream=socket.getInputStream(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); //獲取請求內容 String info; while ((info=bufferedReader.readLine())!=null) { System.out.println("我是服務器端,客戶端請求為:"+info); } socket.shutdownInput(); //服務器端向客戶端回傳信息 OutputStream outputStream=socket.getOutputStream(); PrintWriter printWriter=new PrintWriter(outputStream); printWriter.write("客戶端您好,我已經接受到你的信息"); printWriter.flush(); //關閉資源 printWriter.close(); outputStream.close(); bufferedReader.close(); inputStream.close(); socket.close(); serverSocket.close(); }catch(Exception exception){ } } }客戶端:
package com.socket.demo; 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.net.UnknownHostException; public class Client { public static void main(String[] args) { try { //發送到8888端口 Socket socket=new Socket("127.0.0.1", 8888); //輸出流 OutputStream outputStream=socket.getOutputStream(); PrintWriter printWriter=new PrintWriter(outputStream); printWriter.write("服務器端你好,我是客戶端。"); printWriter.flush(); socket.shutdownOutput();//這個不能少!!!!!!!!!!!!!! //接受服務器端回傳的信息 InputStream inputStream=socket.getInputStream(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String info; while ((info=bufferedReader.readLine())!=null) { System.out.println("我是客戶端,服務器端返回::"+info); } //關閉資源 bufferedReader.close(); inputStream.close(); printWriter.close(); outputStream.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
原因是沒有在客戶端關閉輸出,即這一行代碼:
socket.shutdownOutput();
這裡要注意。