国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
Netty Websocket Server Javascript Client
WebSocket協(xié)議的出現(xiàn)無疑是 HTML5 中最令人興奮的功能特性之一,它能夠很好地替代Comet技術(shù)以及Flash的XmlSocket來實(shí)現(xiàn)基于HTTP協(xié)議的雙向通信。目前主流的瀏覽器,如Chrome、Firefox、IE10、Opera10、Safari等都已經(jīng)支持WebSocket。另外,在服務(wù)端也出現(xiàn)了一些不錯(cuò)的WebSocket項(xiàng)目,如Resin、Jetty7、pywebsocket等。不過,本文將介紹的是如何使用強(qiáng)大的Netty框架(Netty-3.5.7.Final)來實(shí)現(xiàn)WebSocket服務(wù)端。
Netty3框架的性能優(yōu)勢(shì)已無需多說,但更讓開發(fā)者舒心的是,Netty3還為大家提供了非常豐富的協(xié)議實(shí)現(xiàn),包括HTTP、Protobuf、WebSocket等,開發(fā)者們可以很輕松的實(shí)現(xiàn)自己的Socket Server。按照Netty3的常規(guī)思路,我們需要準(zhǔn)備以下3個(gè)文件:
1、WebSocketServer.java
2、WebSocketServerHandler.java
3、WebSocketServerPipelineFactory.java
以上3個(gè)文件分別包含了主程序的邏輯、服務(wù)的處理邏輯以及Socket Pipeline的設(shè)置邏輯。Java代碼實(shí)現(xiàn)如下:
WebSocketServer.java
[java] view plaincopy
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class WebSocketServer
{
private final int port;
public WebSocketServer(int port) {
this.port = port;
}
public void run() {
// 設(shè)置 Socket channel factory
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// 設(shè)置 Socket pipeline factory
bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory());
// 啟動(dòng)服務(wù),開始監(jiān)聽
bootstrap.bind(new InetSocketAddress(port));
// 打印提示信息
System.out.println("Web socket server started at port " + port + '.');
System.out.println("Open your browser and navigate to http://localhost:" + port + '/');
}
public static void main(String[] args) {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new WebSocketServer(port).run();
}
}
WebSocketServerPipelineFactory.java
[java] view plaincopy
import static org.jboss.netty.channel.Channels.*;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
public class WebSocketServerPipelineFactory implements ChannelPipelineFactory {
public ChannelPipeline getPipeline() throws Exception {
// pipeline 的配置與 邏輯
ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", new WebSocketServerHandler());
return pipeline;
}
}
WebSocketServerHandler.java
[java] view plaincopy
import static org.jboss.netty.handler.codec.http.HttpHeaders.*;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
import static org.jboss.netty.handler.codec.http.HttpMethod.*;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.*;
import static org.jboss.netty.handler.codec.http.HttpVersion.*;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import org.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.util.CharsetUtil;
public class WebSocketServerHandler extends SimpleChannelUpstreamHandler
{
private static final InternalLogger logger = InternalLoggerFactory
.getInstance(WebSocketServerHandler.class);
private static final String WEBSOCKET_PATH = "/websocket";
private WebSocketServerHandshaker handshaker;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
// 處理接受消息
Object msg = e.getMessage();
if (msg instanceof HttpRequest) {
handleHttpRequest(ctx, (HttpRequest) msg);
} else if (msg instanceof WebSocketFrame) {
handleWebSocketFrame(ctx, (WebSocketFrame) msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
// 處理異常情況
e.getCause().printStackTrace();
e.getChannel().close();
}
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req)
throws Exception {
// 只接受 HTTP GET 請(qǐng)求
if (req.getMethod() != GET) {
sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1,
FORBIDDEN));
return;
}
// Websocket 握手開始
WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
getWebSocketLocation(req), null, false);
handshaker = wsFactory.newHandshaker(req);
if (handshaker == null) {
wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel());
} else {
handshaker.handshake(ctx.getChannel(), req).addListener(
WebSocketServerHandshaker.HANDSHAKE_LISTENER);
}
}
private void handleWebSocketFrame(ChannelHandlerContext ctx,
WebSocketFrame frame) {
// Websocket 握手結(jié)束
if (frame instanceof CloseWebSocketFrame) {
handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame);
return;
} else if (frame instanceof PingWebSocketFrame) {
ctx.getChannel().write(new PongWebSocketFrame(frame.getBinaryData()));
return;
} else if (!(frame instanceof TextWebSocketFrame)) {
throw new UnsupportedOperationException(String.format("%s frame types not supported",
frame.getClass().getName()));
}
// 處理接受到的數(shù)據(jù)(轉(zhuǎn)成大寫)并返回
String request = ((TextWebSocketFrame) frame).getText();
if (logger.isDebugEnabled()) {
logger.debug(String.format("Channel %s received %s", ctx.getChannel().getId(), request));
}
ctx.getChannel().write(new TextWebSocketFrame(request.toUpperCase()));
}
private static void sendHttpResponse(ChannelHandlerContext ctx,
HttpRequest req, HttpResponse res) {
// 返回 HTTP 錯(cuò)誤頁面
if (res.getStatus().getCode() != 200) {
res.setContent(ChannelBuffers.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8));
setContentLength(res, res.getContent().readableBytes());
}
// 發(fā)送返回信息并關(guān)閉連接
ChannelFuture f = ctx.getChannel().write(res);
if (!isKeepAlive(req) || res.getStatus().getCode() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
private static String getWebSocketLocation(HttpRequest req) {
return "ws://" + req.getHeader(HttpHeaders.Names.HOST) + WEBSOCKET_PATH;
}
}
以上代碼的邏輯還是比較清晰的:首先,在WebSocketServer中設(shè)置WebSocketServerPipelineFactory;然后,在WebSocketServerPipelineFactory中設(shè)置WebSocketServerHandler;接著,在WebSocketServerHandler處理請(qǐng)求并返回結(jié)果;其中,最重要的處理邏輯位于handleWebSocketFrame方法中,也就是把獲取到的請(qǐng)求信息全部轉(zhuǎn)化成大寫并返回。最后,運(yùn)行WebSocketServer.java就可以啟動(dòng)WebSocket服務(wù),監(jiān)聽本地的8080端口。至此,WebSocket服務(wù)端已經(jīng)全部準(zhǔn)備就緒。這里,其實(shí)我們已經(jīng)同時(shí)開發(fā)了一個(gè)簡(jiǎn)單的HTTP服務(wù)器,界面截圖如下:
接下來,我們需要準(zhǔn)備使用Javascript實(shí)現(xiàn)的WebSocket客戶端,實(shí)現(xiàn)非常簡(jiǎn)單,Javascript代碼實(shí)現(xiàn)如下:
websocket.html
[html] view plaincopy
<html><head><title>Web Socket Client</title></head>
<body>
<script type="text/javascript">
var socket;
if (!window.WebSocket) {
window.WebSocket = window.MozWebSocket;
}
// Javascript Websocket Client
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8080/websocket");
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 = "Web Socket opened!";
};
socket.onclose = function(event) {
var ta = document.getElementById('responseText');
ta.value = ta.value + "Web Socket closed";
};
} else {
alert("Your browser does not support Web Socket.");
}
// Send Websocket data
function send(message) {
if (!window.WebSocket) { return; }
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
} else {
alert("The socket is not open.");
}
}
</script>
<h3>Send :</h3>
<form onsubmit="return false;">
<input type="text" name="message" value="Hello World!"/><input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)" />
<h3>Receive :</h3>
<textarea id="responseText" style="width:500px;height:300px;"></textarea>
</form>
</body>
</html>
以上Javascript代碼的邏輯很好理解:即創(chuàng)建一個(gè)指向?qū)?yīng)WebSocket地址(ws://localhost:8080/websocket)的Socket連接,進(jìn)而進(jìn)行發(fā)送和獲取操作。其實(shí),我們只需要把websocket.html文件放置到任意的HTTP服務(wù)器上,并打開對(duì)應(yīng)URL地址,就可以看到以下的Demo界面:
輸入文字“Hello World”并點(diǎn)擊“Send Web Socket Data”按鈕就可以向WebSocket的服務(wù)端發(fā)送消息了。從上圖中我們還可以看到,在“Receive”下方的輸出框中看到返回的消息(大寫過的HELLO WORLD文字),這樣一次基本的信息交互就完成了。當(dāng)然,此時(shí)如果把服務(wù)端關(guān)閉,輸出框中則會(huì)看到“Web Socket closed”信息。
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Netty4實(shí)戰(zhàn)第十一章:WebSockets
websocket與下位機(jī)通過netty方式通信傳輸行為信息
SpringBoot2.0集成WebSocket,實(shí)現(xiàn)后臺(tái)向前端推送信息
Spring+websocket+quartz實(shí)現(xiàn)消息定時(shí)推送
WEB即時(shí)通訊/消息推送
Netty筆記:使用WebSocket協(xié)議開發(fā)聊天系統(tǒng)
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服