当前位置:   article > 正文

使用netty进行客户端和传统的socket进行通讯_netty socket

netty socket

一,服务端以下方式读取数据,则发送的数据必须以换行符/n结尾

String msg = reader.readLine()

1.我们在客户端只要使用传统的客户端编写方式即可

  1. package com.netty.study.nettystart.client;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.buffer.Unpooled;
  5. import io.netty.channel.*;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.oio.OioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioDatagramChannel;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.channel.socket.oio.OioSocketChannel;
  12. import io.netty.handler.codec.string.StringEncoder;
  13. import io.netty.util.CharsetUtil;
  14. import java.net.InetSocketAddress;
  15. import java.nio.charset.Charset;
  16. import java.nio.charset.StandardCharsets;
  17. public class NettyClient {
  18. public static void main(String[] args) {
  19. EventLoopGroup group = new OioEventLoopGroup();
  20. try {
  21. ChannelFuture nettyclient_连接陈工 = new Bootstrap()
  22. .group(group)
  23. .channel(OioSocketChannel.class)
  24. .remoteAddress(new InetSocketAddress("127.0.0.1",9746))
  25. .handler(new ChannelInitializer<SocketChannel>() {
  26. @Override
  27. public void initChannel(SocketChannel nioSocketChannel) throws Exception {
  28. // nioSocketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
  29. nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
  30. @Override
  31. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  32. String message = "Hello Server\n";
  33. ByteBuf buffer = Unpooled.copiedBuffer(message.getBytes());
  34. ctx.writeAndFlush(buffer);
  35. }
  36. @Override
  37. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  38. cause.printStackTrace();
  39. ctx.channel().close();
  40. }
  41. @Override
  42. protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
  43. System.out.println(byteBuf.toString(Charset.defaultCharset()));
  44. }
  45. @Override
  46. public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
  47. super.channelRegistered(ctx);
  48. }
  49. });
  50. }
  51. }).connect().sync();
  52. nettyclient_连接陈工.channel().closeFuture().sync();
  53. } catch (InterruptedException e) {
  54. throw new RuntimeException(e);
  55. } finally {
  56. group.shutdownGracefully();
  57. }
  58. }
  59. }

2.服务端代码

  1. package com.netty.study.nettystart.server;
  2. import java.io.*;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.nio.charset.Charset;
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.Arrays;
  8. public class SimpleSocketServer {
  9. private static final int PORT = 9746;
  10. public static void main(String[] args) throws IOException {
  11. final String QUIT = "quit";
  12. final int DEFAULT_PORT = 9746;
  13. ServerSocket serverSocket = null;
  14. BufferedReader reader = null;
  15. BufferedWriter writer = null;
  16. try {
  17. // 绑定监听端口
  18. serverSocket = new ServerSocket(DEFAULT_PORT);
  19. System.out.println("启动服务器,监听服务器本地端口" + DEFAULT_PORT);
  20. while (true) {
  21. // 等待客户端连接
  22. Socket socket = serverSocket.accept();
  23. System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已连接");
  24. InputStream inputStream = socket.getInputStream();
  25. reader = new BufferedReader(
  26. new InputStreamReader(inputStream)
  27. );
  28. writer = new BufferedWriter(
  29. new OutputStreamWriter(socket.getOutputStream())
  30. );
  31. String msg = reader.readLine();
  32. while (msg != null) {
  33. // 读取客户端发送的消息
  34. System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]: " + msg);
  35. // 回复客户发送的消息
  36. writer.write("服务器已收到: " + msg + "\n");
  37. //防止消息遗留到本地缓冲区,保证马上发送出去
  38. writer.flush();
  39. // 查看客户端是否退出
  40. if (QUIT.equalsIgnoreCase(msg)) {
  41. System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已断开连接");
  42. break;
  43. }
  44. }
  45. // System.out.println(decodedData+"_----------------------------------");
  46. }
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. } finally {
  50. try {
  51. serverSocket.close();
  52. reader.close();
  53. writer.close();
  54. System.out.println("关闭serverSocket");
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }
  60. }

 二,服务端直接以字节数组接收

1.客户端代码和上边一样,唯一的区别就是,不需要固定结尾的/n了,随便发送即可

2.服务端代码:

  1. package com.netty.study.nettystart.server;
  2. import java.io.*;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.nio.charset.Charset;
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.Arrays;
  8. public class SimpleSocketServer {
  9. private static final int PORT = 9746;
  10. public static void main(String[] args) throws IOException {
  11. final String QUIT = "quit";
  12. final int DEFAULT_PORT = 9746;
  13. ServerSocket serverSocket = null;
  14. BufferedReader reader = null;
  15. BufferedWriter writer = null;
  16. try {
  17. // 绑定监听端口
  18. serverSocket = new ServerSocket(DEFAULT_PORT);
  19. System.out.println("启动服务器,监听服务器本地端口" + DEFAULT_PORT);
  20. while (true) {
  21. // 等待客户端连接
  22. Socket socket = serverSocket.accept();
  23. System.out.println("客户端["+socket.getInetAddress()+":"+ socket.getPort() + "]已连接");
  24. InputStream inputStream = socket.getInputStream();
  25. byte[] buffer = new byte[1024];
  26. int bytesRead = inputStream.read(buffer); // 读取字节数据
  27. byte[] receivedData = Arrays.copyOf(buffer, bytesRead); // 接收到的字节数据
  28. // 解码操作,例如将字节数组转换为字符串
  29. String decodedData = new String(receivedData, StandardCharsets.UTF_8);
  30. System.out.println("消息:"+decodedData+"_----------------------------------");
  31. }
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } finally {
  35. try {
  36. serverSocket.close();
  37. reader.close();
  38. writer.close();
  39. System.out.println("关闭serverSocket");
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  45. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/973955
推荐阅读
相关标签
  

闽ICP备14008679号