MyServer
package com.wq.nettylongconnection;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import java.net.InetSocketAddress;
public class MyServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup).
handler(new LoggingHandler(LogLevel.INFO)).
channel(NioServerSocketChannel.class).
childHandler(new WebSocketInitializer());
ChannelFuture channelFuture =serverBootstrap.bind(new InetSocketAddress(8899)).sync();
channelFuture.channel().closeFuture().sync();
}catch(Exception e){
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
WebSocketInitializer
package com.wq.nettylongconnection;
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;
public class WebSocketInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new WebSocketFrameHandler());
}
}
WebSocketFrameHandler
package com.wq.nettylongconnection;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.time.LocalDateTime;
public class WebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("收到消息:"+msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("伺服器時間:"+ LocalDateTime.now()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded"+ctx.channel().id().asLongText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved"+ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("異常發生");
ctx.close();
}
}
html5代碼用戶端
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>WebSocket</title>
</head>
<body>
<script type="text/javascript">
var socket;
if(window.WebSocket){
socket = new WebSocket("ws://localhost:8899/ws");
socket.onmessage = function(event){
var ta = document.getElementById("responseText");
ta.value = ta.value+"\n"+event.data;
}
socket.onopen = function (event) {
var ta = document.getElementById("responseText");
ta.value = "連接配接開啟!";
}
socket.onclose = function (ev) {
var ta = document.getElementById("responseText");
ta.value = ta.value+"\n"+"連接配接關閉!";
}
}else{
alert("浏覽器不支援WebSocket!");
}
function sendMessage(message) {
if(!window.WebSocket){
return;
}
if(socket.readyState==WebSocket.OPEN){
socket.send(message);
}else{
alert("連接配接尚未開啟");
}
}
</script>
<form onsubmit="return false;">
<textarea name="message" style="width:400px;height:200px;"></textarea>
<input type="button" value="發送資料" onclick="sendMessage(this.form.message.value)">
<textarea id="responseText" style="width: 400px;height: 300px;"></textarea>
<input type="button" value="清空内容" onclick="javascript:document.getElementById('responseText').value=''" >
</form>
</body>
</html>