|
| 1 | +package com.bruis.learnnetty.bio; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | +import java.net.Socket; |
| 6 | +import java.util.Scanner; |
| 7 | + |
| 8 | +/** |
| 9 | + * @author LuoHaiYang |
| 10 | + * |
| 11 | + * 在bio的例子中,主要有server端和client端: |
| 12 | + * |
| 13 | + * 1. Server端开启一个线程通过serverSocket.accept()来监听有没有socket连接进来,之列称之为线程A。 |
| 14 | + * 2. 然后在ClientHandler中又开启了一个线程,称为B,用于从socket中获取服务器端传过来的消息,线程B中通过while-true循环来获取。 |
| 15 | + * 3. 在client客户端中,还有一个线程称为C,一直去循环获取服务端的数据。 |
| 16 | + * |
| 17 | + * 在nio中,NioEventLoop源码中的run方法就对应着线程A的while-true方法以及线程c的while-true方法。而NioEventLoop的select方法就对应着serverSocket的accept操作。 |
| 18 | + * |
| 19 | + */ |
| 20 | +public class Client { |
| 21 | + private static final String HOST = "127.0.0.1"; |
| 22 | + private static final int PORT = 8000; |
| 23 | + private static final int SLEEP_TIME = 5000; |
| 24 | + public static final int MAX_DATA_LEN = 1024; |
| 25 | + |
| 26 | + public static void main(String[] args) throws IOException { |
| 27 | + |
| 28 | + final Socket socket = new Socket(HOST, PORT); |
| 29 | + System.out.println("客户端启动成功!"); |
| 30 | + |
| 31 | + while (true) { |
| 32 | + try { |
| 33 | + Scanner scan = new Scanner(System.in); |
| 34 | + String clientMessage = scan.nextLine(); |
| 35 | + System.out.println("客户端发送数据: " + clientMessage); |
| 36 | + socket.getOutputStream().write(clientMessage.getBytes()); |
| 37 | + |
| 38 | + InputStream inputStream = socket.getInputStream(); |
| 39 | + |
| 40 | + byte[] data = new byte[MAX_DATA_LEN]; |
| 41 | + int len; |
| 42 | + while ((len = inputStream.read(data)) != -1) { |
| 43 | + String message = new String(data, 0, len); |
| 44 | + System.out.println("服务器传来消息: " + message); |
| 45 | + |
| 46 | + } |
| 47 | + |
| 48 | + } catch (Exception e) { |
| 49 | + System.out.println("写数据出错!"); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private static void sleep() { |
| 55 | + try { |
| 56 | + Thread.sleep(SLEEP_TIME); |
| 57 | + } catch (InterruptedException e) { |
| 58 | + e.printStackTrace(); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments