WebSocket 서버 및 클라이언트 구축

8860 단어 WebSocket
시장에 몇 가지 비교적 좋은 소스 라이브러리가 있는데 예를 들어PyWebSocket, WebSocket-Node,LibWebSockets 등이다. 이 라이브러리 파일들은 이미 WebSocket 데이터 패키지의 봉인과 해석을 실현했고 우리는 이 인터페이스를 호출하여 작업량을 줄일 수 있다.
1.     PyWebSocket
PyWebSocket은 Python 언어로 작성되어 플랫폼을 뛰어넘고 확장도 간단합니다. 현재 WebKit은 WebSocket 서버를 구축하여 LayoutTest를 하고 있습니다. 참고http://code.google.com/p/pywebsocket/
2.WebSocket-Node
WebSocket-Node는 JavaScript 언어로 작성되었습니다. 이 라이브러리는 nodejs 위에 만들어진 것입니다. 참고https://github.com/Worlize/Websocket-Node
3. LibWebSockets
LibWebSockets는 C/C++ 언어로 작성되어 맞춤형 제작이 가능하며 TCP 감청부터 패키지의 완성까지 프로그래밍에 참여할 수 있습니다.참조하다git://git.warmcat.com/libwebsockets
4.Netty
Netty의 NIO를 사용하여 WebSocket 백엔드를 구축합니다. 참고:https://github.com/netty/netty
하나.Netty로 WebSocket 서버 구축 소개
1.WebsocketChatServer .java
package com.waylau.netty.demo.websocketchat;

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

/**
 * Websocket  - 
 * 
 * @author waylau.com
 * @date 2015-3-7
 */
public class WebsocketChatServer {

    private int port;

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

    public void run() throws Exception {
        
        EventLoopGroup bossGroup = new NioEventLoopGroup(); 
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new WebsocketChatServerInitializer())  // 
             .option(ChannelOption.SO_BACKLOG, 128)          
             .childOption(ChannelOption.SO_KEEPALIVE, true); //  
            
    		System.out.println("WebsocketChatServer  " + port);
    		
            //  , 
            ChannelFuture f = b.bind(port).sync(); // (7)

            //    socket   。
            //  , , 。
            f.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            
    		System.out.println("WebsocketChatServer  ");
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new WebsocketChatServer(port).run();
    }
}
2.서버 ChannelInitializer
package com.waylau.netty.demo.websocketchat;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 *   ChannelInitializer
 *
 * @author
 * @date 2015-3-13
 */
public class WebsocketChatServerInitializer extends
		ChannelInitializer {	//1

	@Override
    public void initChannel(SocketChannel ch) throws Exception {//2
		 ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new HttpObjectAggregator(64*1024));
		pipeline.addLast(new ChunkedWriteHandler());
		pipeline.addLast(new HttpRequestHandler("/ws"));
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		pipeline.addLast(new TextWebSocketFrameHandler());
    }
}
3.TextWebSocketFrame 작업
package com.waylau.netty.demo.websocketchat;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 *  TextWebSocketFrame
 * 
 * @author 
 * 2015 3 26 
 */
public class TextWebSocketFrameHandler extends
		SimpleChannelInboundHandler {
	
	public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx,
			TextWebSocketFrame msg) throws Exception { //  
		Channel incoming = ctx.channel();
		for (Channel channel : channels) {
            if (channel != incoming){
                channel.writeAndFlush(new TextWebSocketFrame(msg.text()));
            } else {
            	channel.writeAndFlush(new TextWebSocketFrame(msg.text()));
            }
        }
	}
	
	@Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {  //  
        Channel incoming = ctx.channel();
        
        // Broadcast a message to multiple Channels
        channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + "  "));
        
        channels.add(incoming);
		System.out.println("Client:"+incoming.remoteAddress() +" ");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {  //  
        Channel incoming = ctx.channel();
        
        // Broadcast a message to multiple Channels
        channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + "  "));
        
		System.out.println("Client:"+incoming.remoteAddress() +" ");

        // A closed Channel is automatically removed from ChannelGroup,
        // so there is no need to do "channels.remove(ctx.channel());"
    }
	    
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception { // 
        Channel incoming = ctx.channel();
		System.out.println("Client:"+incoming.remoteAddress()+" ");
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception { // 
        Channel incoming = ctx.channel();
		System.out.println("Client:"+incoming.remoteAddress()+" ");
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)	//  
			throws Exception {
    	Channel incoming = ctx.channel();
		System.out.println("Client:"+incoming.remoteAddress()+" ");
        //  
        cause.printStackTrace();
        ctx.close();
	}
}
2.,클라이언트




WebSocket Chat


	
		var socket;
		if (!window.WebSocket) {
			window.WebSocket = window.MozWebSocket;
		}
		if (window.WebSocket) {
			socket = new WebSocket("ws://192.169.1.101:8080/ws");
			socket.onmessage = function(event) {
				var ta = document.getElementById('responseText');
				ta.value = ta.value + '
' + event.data }; socket.onopen = function(event) { var ta = document.getElementById('responseText'); ta.value = " !"; }; socket.onclose = function(event) { var ta = document.getElementById('responseText'); ta.value = ta.value + " "; }; } else { alert(" WebSocket!"); } function send(message) { if (!window.WebSocket) { return; } if (socket.readyState == WebSocket.OPEN) { socket.send(message); } else { alert(" ."); } }

WebSocket 채팅방:

좋은 웹페이지 즐겨찾기