上机题目(0基础)- Java网络操作-Socket实现client和server端通信二(Java)
上一节实现了client像server端发送请求。本节将实现server端向client回传信息。实现原理非常easy,在原来的基础上。在server端实现输出流,在client实现输入流就可以,详细代码例如以下:
server端:
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("我是server端。client请求为:"+info); } socket.shutdownInput(); //server端向client回传信息 OutputStream outputStream=socket.getOutputStream(); PrintWriter printWriter=new PrintWriter(outputStream); printWriter.write("client您好。我已经接受到你的信息"); printWriter.flush(); //关闭资源 printWriter.close(); outputStream.close(); bufferedReader.close(); inputStream.close(); socket.close(); serverSocket.close(); }catch(Exception exception){ } } }client:
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("server端你好,我是client。"); printWriter.flush(); socket.shutdownOutput();//这个不能少。!
!
!
!!!。!!。!
!
! //接受server端回传的信息 InputStream inputStream=socket.getInputStream(); BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream)); String info; while ((info=bufferedReader.readLine())!=null) { System.out.println("我是client。server端返回::"+info); } //关闭资源 bufferedReader.close(); inputStream.close(); printWriter.close(); outputStream.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
执行实比例如以下:
server控制台输出:
posted on 2017-07-27 19:30 cynchanpin 阅读(742) 评论(0) 编辑 收藏 举报