WebSocket 서버 및 클라이언트 구축
8860 단어 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.서버 ChannelInitializerpackage 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(" .");
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
WebSocket+spring 예제 demo 자세히 보기(sockJs 라이브러리 사용)예를 들어 Canvas, 로컬 저장소, 멀티미디어 프로그래밍 인터페이스, WebSocket 등이다.이 중'웹의 TCP'라고 불리는 웹소켓은 특히 개발자들의 주의를 끈다.WebSocket의 등장으로 브라우저가 Sock...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.