undertow에서 WebSocket 실행 간단한 실례

3792 단어 websocketundertow
1. WebSocket 서버 만들기:
import static io.undertow.Handlers.path;
import static io.undertow.Handlers.resource;
import static io.undertow.Handlers.websocket;
import io.undertow.Undertow;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.AbstractReceiveListener;
import io.undertow.websockets.core.BufferedTextMessage;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.core.WebSockets;
import io.undertow.websockets.spi.WebSocketHttpExchange;

public class WebSocketServer {

	public static void main(final String[] args) {
		Undertow server = Undertow
				.builder()
				.addListener(8080, "0.0.0.0")
				.setHandler(
						path().addPrefixPath("/websocket",
								websocket(new WebSocketConnectionCallback() {

									@Override
									public void onConnect(
											WebSocketHttpExchange exchange,
											WebSocketChannel channel) {
										channel.getReceiveSetter().set(
												new AbstractReceiveListener() {

													@Override
													protected void onFullTextMessage(
															WebSocketChannel channel,
															BufferedTextMessage message) {
														WebSockets.sendText(
																message.getData(),
																channel, null);
													}
												});
										channel.resumeReceives();
									}
								})).addPrefixPath(
								"/",
								resource(
										new ClassPathResourceManager(
												WebSocketServer.class
														.getClassLoader(),
												WebSocketServer.class
														.getPackage()))
										.addWelcomeFiles("index.html")))
				.build();
		server.start();

	}

}

 2.페이지 파일 index를 만듭니다.html
<html>
<head><title>Web Socket Test</title>
<meta name="viewport" content="width=device-width">
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {
        socket = new WebSocket("ws://192.168.1.11:8080/websocket");
        socket.onmessage = function(event) {
            alert("Received data from websocket: " + event.data);
        };
        socket.onopen = function(event) {
            alert("Web Socket opened!");
        };
        socket.onclose = function(event) {
            alert("Web Socket closed.");
        };
    } else {
        alert("Your browser does not support Websockets. (Use Chrome)");
    }

    function send(message) {
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("The socket is not open.");
        }
    }
</script>
<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)"/>
</form>
</body>
</html>

 3.브라우저에 다음을 입력합니다.http://ip:8080휴대폰과 컴퓨터 모두 액세스 가능
 
참조:
http://www.ibm.com/developerworks/cn/web/1112_huangxa_websocket/

좋은 웹페이지 즐겨찾기