网络编程--(四)Netty部署测试

 

服务端程序分开部署

网络编程--(四)Netty部署测试_第1张图片

 

复制代码
package bhz.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {

    public static void main(String[] args) throws Exception {
        //1 第一个线程组 是用于接收Client端连接的
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2 第二个线程组 是用于实际的业务处理操作的
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        
        //3 创建一个辅助类Bootstrap,就是对我们的Server进行一系列的配置
        ServerBootstrap b = new ServerBootstrap(); 
        //把俩个工作线程组加入进来
        b.group(bossGroup, workerGroup)
        //我要指定使用NioServerSocketChannel这种类型的通道
         .channel(NioServerSocketChannel.class)
        //一定要使用 childHandler 去绑定具体的 事件处理器
         .childHandler(new ChannelInitializer() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ServerHandler());
            } 
        });

        //绑定指定的端口 进行监听
        ChannelFuture f = b.bind(8765).sync(); 
        ChannelFuture f2 = b.bind(8764).sync(); 
        
        //Thread.sleep(1000000);
        f.channel().closeFuture().sync();   //等待关闭
        f2.channel().closeFuture().sync();
        
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
         
        
        
    }
    
}
复制代码
复制代码
package bhz.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ServerHandler  extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    
            //do something msg
            ByteBuf buf = (ByteBuf)msg; 
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String request = new String(data, "utf-8");
            System.out.println("Server: " + request);
            //写给客户端
            String response = "我是反馈的信息";
            ctx.writeAndFlush(Unpooled.copiedBuffer("888".getBytes()))
            .addListener(ChannelFutureListener.CLOSE);   //当服务器端写完客户端收到后断开客户端连接
            

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
复制代码
复制代码
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>deploygroupId>
  <artifactId>deployartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>jarpackaging>

  <name>deployname>
  <url>http://maven.apache.orgurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
  properties>
    
  <build>
      <pluginManagement>
          <plugins>
          
              <plugin>
                  <groupId>org.eclipse.m2egroupId>
                  <artifactId>lifecycle-mappingartifactId>
                  <version>1.0.0version>
                  <configuration>
                      <lifecycleMappingMetadata>
                          <pluginExecutions>
                              <pluginExecution>
                                  <pluginExecutionFilter>
                                       <groupId>org.apache.maven.pluginsgroupId>
                                     <artifactId>maven-dependency-pluginartifactId>
                                     <versionRange>[2.0,)versionRange>
                                     <goals>
                                         <goal>copy-dependenciesgoal>
                                     goals>
                                  pluginExecutionFilter>
                                  <action>
                                      <ignore/>
                                  action>
                              pluginExecution>
                          pluginExecutions>
                      lifecycleMappingMetadata>
                  configuration>
              plugin>
          plugins>
      pluginManagement>
      
      <plugins>
          
          <plugin>
              <groupId>org.apache.maven.pluginsgroupId>
              <artifactId>maven-jar-pluginartifactId>
              <configuration>
                  <classesDirectory>target/classesclassesDirectory>
                  <archive>
                      <manifest>
                          
                          <mainClass>bhz.netty.test.ServermainClass>
                          
                          <useUniqueVersions>falseuseUniqueVersions>
                          <addClasspath>trueaddClasspath>
                          
                          <classpathPrefix>libclasspathPrefix>
                      manifest>
                      <manifestEntries>
                          <Class-Path>.Class-Path>
                      manifestEntries>
                  archive>
              configuration>
          plugin>
          <plugin>
              <groupId>org.apache.maven.pluginsgroupId>
              <artifactId>maven-dependency-pluginartifactId>
              <executions>
                  <execution>
                      <id>copy-dependenciesid>
                      <phase>packagephase>
                      <goals>
                          <goal>copy-dependenciesgoal>
                      goals>
                      <configuration>
                          <type>jartype>
                          <includeTypes>jarincludeTypes>
                          <useUniqueVersions>falseuseUniqueVersions>
                          
                          <outputDirectory>
                              ${project.build.directory}/lib
                          outputDirectory>
                      configuration>
                  execution>
              executions>
          plugin>
          
      plugins>
      
  build>
      
  <dependencies>
    <dependency>
        <groupId>io.nettygroupId>
        <artifactId>netty-allartifactId>
        <version>5.0.0.Alpha1version>
    dependency>
    

  dependencies>
project>
复制代码

 run as>maven install

网络编程--(四)Netty部署测试_第2张图片

只需要 deploy-0.0.0-SNAPSHOT.jar 和lib文件夹放到服务器上启动jar即可

网络编程--(四)Netty部署测试_第3张图片

java -jar  deploy-0.0.1-SNAPSHOT.jar

网络编程--(四)Netty部署测试_第4张图片

 

 客户端程序

复制代码
package bhz.netty.test;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {

    public static void main(String[] args) throws Exception {
        
        EventLoopGroup workgroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(workgroup)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new ClientHandler());
            }
        });
        
        ChannelFuture cf1 = b.connect("127.0.0.1", 8765).sync();
        ChannelFuture cf2 = b.connect("127.0.0.1", 8764).sync();
        
        //写入
        cf1.channel().writeAndFlush(Unpooled.copiedBuffer("777".getBytes()));
        cf2.channel().writeAndFlush(Unpooled.copiedBuffer("111".getBytes()));
        
        cf1.channel().closeFuture().sync();
        cf2.channel().closeFuture().sync();
        workgroup.shutdownGracefully();
        
    }
}
复制代码
复制代码
package bhz.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            //do something msg
            ByteBuf buf = (ByteBuf)msg;
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String request = new String(data, "utf-8");
            System.out.println("Client: " + request);
            
            
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
复制代码

 

你可能感兴趣的:(Socket)