1. package io.torey.niotest;
  2. import java.io.IOException;
  3. import java.net.InetSocketAddress;
  4. import java.nio.channels.SocketChannel;
  5. import java.nio.charset.Charset;
  6. import java.util.Scanner;
  7. /**
  8. * NIO客户端
  9. */
  10. public class NioClient {
  11. /**
  12. * 启动
  13. */
  14. public void start() throws IOException {
  15. //连接服务器端
  16. //向服务器端发送数据
  17. //接收服务器端相应
  18. //连接服务器端
  19. SocketChannel socketChannel = SocketChannel.open(
  20. new InetSocketAddress("127.0.0.1", 8000));
  21. //向服务器端发送数据
  22. Scanner scanner = new Scanner(System.in);
  23. while (scanner.hasNextLine()) {
  24. String request = scanner.nextLine();
  25. if (null!= request&&request.length()>0) {
  26. socketChannel.write(Charset.forName("UTF-8").encode(request));
  27. }
  28. }
  29. //接收服务器端相应
  30. }
  31. public static void main(String[] args){
  32. try {
  33. NioClient nioClient = new NioClient();
  34. nioClient.start();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. }

这时候就可以开启服务器端和客户端,发送一下消息了

image.png
image.png