2014-09-04 3 views
-1

Netio를 사용하여 서버를 변경하여 nio를 지원합니다. nio를 지원하기 위해 클라이언트를 변경해야하거나 그대로 작동 할 수 있습니까?서버를 차단하고 클라이언트를 차단할 수 있습니까?

EDIT : 작은 테스트를 작성했지만 서버로 데이터를 보낼 수 있지만 클라이언트가 서버로 보낸 데이터를받지 못했습니다. (바이트 []) 메시지를 수신하지 않습니다

try{ 
     socket = new Socket("127.0.0.1", 5552); 
     out = new PrintWriter(socket.getOutputStream(), true); 
     in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
     input = new DataInputStream(socket.getInputStream()); 
    } catch (UnknownHostException e) { 
     System.out.println("Unknown host"); 
     System.exit(1); 
    } catch (IOException e) { 
     System.out.println("No I/O"); 
     System.exit(1); 
    } 
out.println(text); 
     System.out.println("Data Sent :" + text); 


//Receive text from server 
     try{ 
     //String line = in.readLine(); 
      byte[] buffer =new byte[100]; 
      int bytes = input.read(buffer); 
      System.out.println("Data Received From Server :" + new String(buffer)); 
     } catch (IOException e){ 
    System.out.println("Read failed"); 
     System.exit(1); 
     } 

주 내의 readLine 모두 읽기 : 서버 :

public class NettyNioServer { 
    private static final int BACKLOG = 1000; 
    private final int port; 

    public NettyNioServer(int port){ 
     this.port = port; 
    } 

    public void start() throws Exception{ 
     EventLoopGroup bossGroup = new NioEventLoopGroup(); 
     EventLoopGroup workerGroup = new NioEventLoopGroup(); 
     try{ 
      final ChannelInitializer<SocketChannel> channelInitializer = new BasicSocketChannelInitializer(); 
      ServerBootstrap b = new ServerBootstrap(); 
      b.group(bossGroup, workerGroup) 
      .channel(NioServerSocketChannel.class) 
      .childHandler(channelInitializer) 
      .option(ChannelOption.SO_BACKLOG, BACKLOG) 
      .option(ChannelOption.SO_KEEPALIVE, true); 
      ChannelFuture f = b.bind(port).sync(); 
      System.out.println("* * * Mediation Server Started on Port: "+port+" * * *"); 
      Main.getLogWrapper1().log(Level.INFO, "* * * Mediation Server Started on Port: "+port+" * * *"); 
      f.channel().closeFuture().sync(); 
     }catch(Exception e){ 
      Main.getLogWrapper1().log(Level.FATAL, "***** Could not listen on Port ****"); 
      StringWriter sw = new StringWriter(); 
      e.printStackTrace(new PrintWriter(sw)); 
      Main.getLogWrapper1().log(Level.FATAL, sw.toString()); 
      e.printStackTrace(); 
     }finally{ 
      workerGroup.shutdownGracefully(); 
      bossGroup.shutdownGracefully(); 
     } 
    } 
} 

public class BasicNioServerHandler extends ChannelInboundHandlerAdapter{ 

    @Override 
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
     String message = (String) msg; 
     try{ 
      System.out.println(message); 
      if (message != null && message.length()>0) { 
       //New Code Start Here 
       FrameProcessor frameProcessor = new FrameProcessor(null,Main.getLogWrapper1(),new Util()); 
       final String msgResponse = frameProcessor.frameDataProcess(message,"");    
       final ChannelFuture f = ctx.writeAndFlush(msgResponse+"\r\n"); 
       f.addListener(new ChannelFutureListener() { 
        @Override 
        public void operationComplete(ChannelFuture future) throws Exception { 
         System.out.println("Message Sent to COMM: ACK="+msgResponse); 
        } 
       }); 

      } 
     }finally{ 
      ReferenceCountUtil.release(msg); 
     } 
    } 

    @Override 
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 
     cause.printStackTrace(); 
     Main.getLogWrapper1().log(Level.ERROR, cause.getMessage()); 
     //ctx.close(); 
    } 
} 

public class BasicSocketChannelInitializer extends ChannelInitializer<SocketChannel>{ 

    private static final StringDecoder STRING_DECODER = new StringDecoder(CharsetUtil.UTF_8); 
    private static final StringEncoder STRING_ENCODER = new StringEncoder(CharsetUtil.UTF_8); 

    @Override 
    protected void initChannel(SocketChannel ch) throws Exception { 
     ChannelPipeline pipeline = ch.pipeline(); 
     //Decoders 
     pipeline.addLast("frameDecoder", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); 
     pipeline.addLast("stringDecoder", STRING_DECODER); 
     pipeline.addLast(new BasicNioServerHandler()); 
     //Encoders 
     pipeline.addLast("stringEncoder", STRING_ENCODER); 
    } 

} 

차단 클라이언트를

아래의 코드 샘플을 참조하십시오. ChannelFuture는 메시지가 성공적으로 전송 된 것으로 인쇄합니다. 또한 간단한 문자열, 문자열 + "\ r \ n", 문자열 + "\ n"을 보냈지 만 클라이언트에서 메시지를받지 못했습니다.

답변

0

예. 그것은 모두 TCP입니다. 블로킹/비 블로킹/비동기는 프로토콜이 아닌 API의 속성입니다.

+0

편집 된 질문을보고 고객으로 응답을받을 수없는 이유를 알려주십시오. – gladiator

+0

지금 완전히 다른 질문을하고 있습니다. 아무 것도 보내지 않았다는 어떠한 증거도 제공하지 않았습니다. 당신은 싱글이 있어야하는 이중 백 슬래쉬를 가지고 있습니다. – EJP

관련 문제