码迷,mamicode.com
首页 > 编程语言 > 详细

Java基础学习03--BIO基本使用

时间:2020-12-24 11:56:58      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:服务端   input   throws   span   div   刷新   获取   bsp   rgb   

1.单服务端,单客户端的Sokect通信:

Server端:

 1 package socket.demo.singlethread;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStream;
 5 import java.io.InputStreamReader;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 public class Server {
10     public static void main(String[] args) {
11         try {
12             //1.定义一个ServerSocket对象进行服务端的端口注册
13             ServerSocket serverSocket = new ServerSocket(9999);
14 
15             //2.监听客户端的sokcet链接请求
16             Socket socket = serverSocket.accept();
17 
18             //3.从客户端得到一个字节输入流对象
19             InputStream inputStream = socket.getInputStream();
20 
21             //4.把字节输入流包装成缓冲字节输入流
22             //BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
23 
24             //4.把字节输入流包装成缓冲字节输入流
25             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
26             String msg;
27             while ((msg = bufferedReader.readLine()) != null) {
28                 System.out.println("服务端接收到:" + msg);
29             }
30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33     }
34 }

Client端:

 1 package socket.demo.singlethread;
 2 
 3 import java.io.IOException;
 4 import java.io.OutputStream;
 5 import java.io.PrintStream;
 6 import java.net.Socket;
 7 
 8 public class Client {
 9     public static void main(String[] args) throws IOException {
10         //1.创建Sokcet对象请求服务端
11         Socket socket = new Socket("127.0.0.1", 9999);
12 
13         //2.从Socket对象中获取一个字节输出流
14         OutputStream outputStream = socket.getOutputStream();
15 
16         //3.把字节输出流包装成打印流
17         PrintStream printStream = new PrintStream(outputStream);
18 
19         //打印
20         printStream.println("hello world");
21 
22         //刷新
23         printStream.flush();
24     }
25 }

 

Java基础学习03--BIO基本使用

标签:服务端   input   throws   span   div   刷新   获取   bsp   rgb   

原文地址:https://www.cnblogs.com/asenyang/p/14159959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!