Develop
2015.01.02 18:23
[java] netty (비동기 이벤트 방식 네트워크 프레임워크) 사용법 #1 (server)
조회 수 4400 댓글 1
비동기 이벤트 방식으로 (listener 방식 및 nio) 지원 되는 간단한 framework 가 있어서 정리를
해봅니다. 꼭 한번 다뤄 보고 싶었던 녀석이었는데 이번에 다루게 되네요.
전 이걸 push 서버에다 집어 넣을 생각입니다~~ 생각만 해도 즐겁네요.
일단 서버 쪽 소스를 올려 놓고 2차로 클라이언트 소스를 올려 보겠습니다.
이 녀석의 다운로드는 http://netty.io/ 에서 받으시면 됩니다. (이 녀석 참 파란만장 합니다. apache
mina 부터 시작 해서 jboss 로 갔다가 독립한 모양입니다. 더 대단한건 한국 분이 만드셨답니다~)
어쨌든 소스를 보시면 바로 응용해서 무언가를 만드실 수 있을 겁니다.
전 일단 소켓을 이용한 byte 통신에 필요한 거라 아래 정도만 정리 하는데 다른 점이 필요 하신
분들은 위의 다운로드 사이트에 가서 메뉴얼을 읽어 보시는 게 좋겠습니다.
제 소스는 퀵 스타트 정도로만 보시면 괜찮겠네요.
일단 서버쪽에 클래스 2개가 필요한데
첫번째로 이벤트 핸들러 클래스를 정리 해 보면
package netty.test;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
public class SimpleServerHandler extends SimpleChannelHandler
{
@Override
public void messageReceived(ChannelHandlerContext ctx,MessageEvent e)
{
ChannelBuffer request = (ChannelBuffer)e.getMessage();
byte[] message = request.array();
System.out.println("message:"+new String(message));
//request 메시지 찍어보기
if(new String(message).equals("1234a"))
{
ChannelBuffer response = ChannelBuffers.dynamicBuffer();
response.writeBytes("server write test".getBytes());
ChannelFuture future = e.getChannel().write(response);
}
}
public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e)
{
e.getCause().printStackTrace();
Channel ch = e.getChannel();
ch.close();
}
}두 번째로 서버를 실행 시키는 main 클래스 로직을 살펴 보면
package netty.test;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class SimpleServer
{
/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
ChannelFactory factory = new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()
);
//socket 을 nio 를 이용한 channel pool 로 관리 한다.
ServerBootstrap bootstrap = new ServerBootstrap(factory);
bootstrap.setPipelineFactory(new ChannelPipelineFactory()
{
@Override
public ChannelPipeline getPipeline() throws Exception
{
// TODO Auto-generated method stub
return Channels.pipeline(new SimpleServerHandler());
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress(8000));
//열릴 port 가 8000 이라는 뜻입니다.
//서버일 경우 bind 를 쓰고 클라이언트일 경우 connect 로 메소드를 쓴다.
}
}[출처] http://shonm.tistory.com/397
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 수 |
|---|---|---|---|---|---|
| 265 | Develop |
[android] 가속도 센서를 이용한 흔듦(Shake) 감지
|
hooni | 2014.11.04 | 3146 |
| 264 | Develop | [ios] 스크린 캡쳐 (전원버튼 + 홈버튼) 호출 알아내기 | hooni | 2014.11.19 | 2705 |
| 263 | Develop | [ios] 비동기 블럭 코드 예제 | hooni | 2014.11.21 | 1676 |
| 262 | System/OS | [svn] SVN trunk 변경사항 되돌리기 (SVN Rollback) | hooni | 2014.11.27 | 2712 |
| 261 | System/OS | [svn] Can't convert string from native encoding to 'UTF-8' 메시지가 나오는 경우 | hooni | 2014.12.18 | 2279 |
| 260 | System/OS |
iptime 공유기 해킹 기술문서
4 |
hooni | 2015.01.01 | 3738 |
| 259 | Develop |
ZBar 라이브러리를 이용한 바코드 스캔 앱 개발하기
|
hooni | 2015.01.01 | 2818 |
| 258 | System/OS | [svn] 하나의 SVN에서 멀티 저장소 (One svnserve, multiple repositories) | hooni | 2015.01.02 | 2751 |
| » | Develop | [java] netty (비동기 이벤트 방식 네트워크 프레임워크) 사용법 #1 (server) 1 | hooni | 2015.01.02 | 4400 |
| 256 | Develop | [java] netty (비동기 이벤트 방식 네트워크 프레임워크) 사용법 #2 (client) | hooni | 2015.01.02 | 3639 |
| 255 | System/OS | CentOS 에서 Cacti 설치하기 | hooni | 2015.01.02 | 3293 |
| 254 | Develop | [android] 안드로이드 동영상 스트리밍 예제 2 | hooni | 2015.01.02 | 6352 |
전 io. netty밖에 안생겨서 SimpleChannelHandler이랑 @ChannelPipelineCoverage("all"), MessageEvent가 에러가 납니다 ㅜㅜ
그리고, messageReceived랑 channelRead랑 다른점이 뭔가요?