Java netty 与 Egret WebSock通信

来源:互联网 发布:怎样免费开淘宝网店 编辑:程序博客网 时间:2024/06/10 16:26
刚开始学java和html5 看到websocket 准备写个通信。发现遇到问题  先把代码放上:服务器 java-netty   4.x后

===========================主文件:

public class Main {public static void main(String[] args) {new NettyService().start();System.out.println("start run server...");}}


=========================================
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;public class NettyService {private ServerBootstrap server;public void start(){EventLoopGroup bossgroup = new NioEventLoopGroup();EventLoopGroup workgroup = new NioEventLoopGroup();try{server = new ServerBootstrap();server.group(bossgroup, workgroup);server.channel(NioServerSocketChannel.class);server.childHandler(new WebSockChannelInitalizer());server.option(ChannelOption.SO_BACKLOG, 128);server.childOption(ChannelOption.SO_KEEPALIVE, true);ChannelFuture f = server.bind(5566).sync();f.channel().closeFuture().sync();}catch(Exception e){System.out.println("server start fiald ... error:\n"+e.getMessage());}finally{bossgroup.shutdownGracefully();workgroup.shutdownGracefully();System.out.println("server start end");}}}


====================================

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;public class WebSockChannelInitalizer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel sockchannel) throws Exception {// TODO Auto-generated method stubChannelPipeline channel = sockchannel.pipeline();channel.addLast(new HttpServerCodec());channel.addLast(new HttpObjectAggregator(64*1024));channel.addLast(new WebSocketServerProtocolHandler("/ws", null, true));channel.addLast(new WebSockServerHandler());}}


================================
import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;import io.netty.handler.codec.http.websocketx.WebSocketFrame;public class WebSockServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame)throws Exception {System.out.println("接收到客户端数据");Channel ch = ctx.channel();if (frame instanceof TextWebSocketFrame) {TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;String text = textFrame.text();System.out.println("WebSocket Server received message: " + text);ch.writeAndFlush(new TextWebSocketFrame(text.toUpperCase()));} else {String message = "不支持的 frame类型: " + frame.getClass().getName();throw new UnsupportedOperationException(message);}}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("客户端与服务器链接");}@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {// TODO Auto-generated method stubsuper.channelInactive(ctx);System.out.println("客户端与服务器断开链接");}}



////////////////////////////////////////////////////////////////////////////
Egret 
////////////////////////////////////////////////////////////////////////////
class Main extends egret.DisplayObjectContainer {    public constructor() {        super();        this.once(egret.Event.ADDED_TO_STAGE, this.handleInitStage, this);    }    private sock:GameSock;    private handleInitStage(e:egret.Event)    {        this.sock = new GameSock();    }}


=======================================
class GameSock {private sock:egret.WebSocket;public constructor() {this.sock = new egret.WebSocket();this.sock.addEventListener(egret.Event.CONNECT, this.handleConnect, this);this.sock.addEventListener(egret.ProgressEvent.SOCKET_DATA, this.handleRecvData, this);this.sock.addEventListener(egret.IOErrorEvent.IO_ERROR, this.handleIoError, this);// this.sock.connect("echo.websocket.org", 80);this.sock.connectByUrl("ws://localhost:5566/ws");}private handleConnect(){console.log("链接成功");this.sock.writeUTF("hello netty");}private handleRecvData(e:egret.Event){var msg = this.sock.readUTF();   console.log("接受数据" + msg);}private handleIoError(){console.log("io Error");}}



原创粉丝点击