2017-11-17 8 views
0

서버에서 데이터를 송수신하는 기본 Netty Client를 작성했습니다. 하지만 포트 8080과 8081에서 클라이언트의 두 인스턴스를 시작했습니다. 이제 어떻게 특정 문자열을 8080 포트와 8081 포트로 보낼 수 있습니까? 특정 포트에서 데이터를 보내는 방법이 혼란 스럽습니다. 모든 문자열을 서버에 보낼 수 있습니다. 하지만 어떤 문자열을 서버로 보낼지 지정하고 싶습니다. 마찬가지로 "Hello server1"을 포트 8080의 server1에 보내고 "Hello server2"를 포트 8081의 server2로 보내고 싶습니다. 어떻게하면됩니까?다른 포트에서 실행중인 특정 Netty Client 인스턴스에서 데이터를 보내는 방법

내 인 Netty 클라이언트 :

public class Client implements Runnable { 

public int port; 

private Channel channel; 
public ChannelFuture channelFuture = null; 
private String message; 
int rcvBuf, sndBuf, lowWaterMark, highWaterMark; 

public Client(int port) { 

    this.port = port; 
    rcvBuf = Integer.MAX_VALUE; 
    sndBuf = Integer.MAX_VALUE; 
    lowWaterMark = 2048; 
    highWaterMark = 3048; 

} 

@Override 
public void run() { 

    try { 
     connectLoop(); 
    } catch (Exception ex) { 

     System.err.println("Exception raised in Client class" + ex); 
    } 

} 

public final void connectLoop() throws InterruptedException { 
    EventLoopGroup workGroup = new NioEventLoopGroup(); 

    try { 
     Bootstrap bs = new Bootstrap(); 
     bs.group(workGroup); 
     bs.channel(NioSocketChannel.class); 
     bs.option(ChannelOption.SO_KEEPALIVE, true) 
       .option(ChannelOption.SO_RCVBUF, rcvBuf) 
       .option(ChannelOption.SO_SNDBUF, sndBuf) 
       .option(ChannelOption.SO_LINGER, 0) 
       .option(ChannelOption.SO_KEEPALIVE, true) 
       .option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark(lowWaterMark, highWaterMark)) 
       .option(ChannelOption.TCP_NODELAY, true) 
       .handler(new ChannelInitializer<SocketChannel>() { 
        @Override 
        protected void initChannel(SocketChannel socketChannel) { 
         socketChannel.pipeline() 
           .addLast("patternDecoder", new ClientDecoder()) 
           .addLast("Response Handler", new ClientHandler())// for receiving from Server 
           .addLast("exception Handler", new ClientExceptionHandler(port)); 
        } 
       }); 

     channelFuture = bs.connect("127.0.0.1", port).sync(); 
     this.channel = channelFuture.channel(); 
     if (channelFuture.isSuccess()) { 
      sendMessage("Hello server"); 
     } 
    } catch (Exception ex) { 

     workGroup.shutdownGracefully(); 
     System.err.println("ERROR : Server Not In Connection"); 
     System.err.println("Connecting to Server..."); 
        reconnect(); 
    } 

} 

public void reconnect() throws InterruptedException { 
    Thread.sleep(10000); 
    connectLoop(); 

} 

public void sendMessage(String data){ 
    if (data != null) 
    { 
     channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(data.getBytes())); 
     System.out.println("Outgoing To Server >> " + data); 
    } 
} 
public static void main(String[] args){ 
    Thread t = new Thread(new Client(8080)); 
    t.start(); 
    Thread t1 = new Thread(new Client(8081)); 
    t1.start(); 
} 

}

클라이언트 핸들러

public class ClientHandler extends SimpleChannelInboundHandler<String> { 

    @Override 
    protected void channelRead0(ChannelHandlerContext ctx, final String message) throws Exception { 

     System.out.println("Incoming From Server >> " + message); 
     ctx.channel().writeAndFlush(Unpooled.wrappedBuffer("HELLO".getBytes())); 
    } 
} 

ClientExceptionHandler

public class ClientExceptionHandler extends ChannelInboundHandlerAdapter { 

    private int port; 
    public ClientExceptionHandler(int port){ 
     this.port = port; 
    } 
    @Override 
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 

     ctx.deregister(); 
     ctx.disconnect(); 
     ctx.close(); 
     System.err.println("ERROR : Server Disconnected"); 
     System.err.println("Reconnecting to Server..."); 
    } 
} 

답변

1

먼저 포트가 작동하는 방식을 이해해야합니다. 서버 만 특정 포트에서 수신 대기합니다. 예제에서 서버는 포트 8080에서 수신 대기합니다. 그러면 여러 클라이언트가 포트 8080에 연결할 수 있습니다. 특정 세부 사항을 제공하지 않았으므로 다음 중 하나를 시도해보십시오.

  • 하나는 포트 8080을 청취하고 다른 하나는 포트 8081을 청취합니다. 그런 다음 제안한대로 두 개의 클라이언트를 사용하십시오. 포트
  • 실행 하나 개의 서버 8080 및
(예를 들어, 서버에 클라이언트 ID를 전송) 클라이언트가 어떤 종류의 메시지를 사용하여 구별하려면 두 개의 유사한 클라이언트 연결