* Maven dependency 추가


<dependency>

<groupId>org.java-websocket</groupId>

<artifactId>Java-WebSocket</artifactId>

<version>1.5.1</version>

</dependency>


1. TestEndpointServer.java (Websocket Server)


import javax.websocket.OnClose;

import javax.websocket.OnError;

import javax.websocket.OnMessage;

import javax.websocket.OnOpen;

import javax.websocket.server.ServerEndpoint;


/**

 * Websocket Test Server

 */

@ServerEndpoint("/websocket")

public class TestEndpointServer {

/**

* 웹 소켓이 연결되었을 때 호출(또는 URL 접근시 호출)

*/

@OnOpen

public void connectionOpen() {

System.out.println("################# client is connected!");

}


/**

* 웹 소켓에서 메시지가 날라왔을 때 호출

* cf) 메세지를 받기만 할 경우 return 값을 void로 설정

*/

@OnMessage

public String receiveMessage(String message) {

System.out.println("################# Message from the client : " + message);

String sendMessage = "return message " + message + " -> Lucky Number : " + Math.floor(Math.random() * 100);

System.out.println("################# Echo from the server : " + sendMessage);

return sendMessage;

}


/**

* 웹 소켓이 닫혔을 때 호출(또는 브라우저가 닫혔을 때 호출)

*/

@OnClose

public void connectionClose() {

System.out.println("################# client is disconnected!");

}


/**

* 웹 소켓이 에러가 났을 때 호출

* @param t

*/

@OnError

public void connectionError(Throwable t) {

t.printStackTrace();

}

}


2-1. TestEndpointClient.java (Websocket Client : java 테스트용 1. 서버를 띄운뒤 2-1, 2-2 같이 작성해서 돌려야됨)


import java.io.IOException;

import java.net.URI;


import javax.websocket.ClientEndpoint;

import javax.websocket.ContainerProvider;

import javax.websocket.OnOpen;

import javax.websocket.Session;

import javax.websocket.WebSocketContainer;


/**

 * Websocket Test Client

 */

@ClientEndpoint

public class TestEndpointClient {

public String SocketIp = "127.0.0.1";

public String SocketPort = "7200";

public String SocketPath = "/websocket";


Session userSession = null;


/**

* Websocket 연결

*/

public TestEndpointClient() {

try {

WebSocketContainer container = ContainerProvider.getWebSocketContainer();

container.connectToServer(this, new URI("ws://" + SocketIp + ":" + SocketPort + SocketPath));

} catch (Exception e) {

throw new RuntimeException(e);

}

}


/**

* 웹 소켓이 연결되었을 때 호출

*/

@OnOpen

public void onOpen(Session userSession) {

System.out.println("################# open Websocket");

this.userSession = userSession;

}


/**

* 웹 소켓 닫기

* @OnClose을 사용하였으나 연결이 끈기지 않어(왜?) 직접 연결끈기...ㅜ.ㅡ

*/

public void onClose() {

System.out.println("################# close Websocket");

try {

if(this.userSession != null) {

this.userSession.close();

}

} catch (IOException e) {

e.printStackTrace();

}

finally {

this.userSession = null;

}

}


/**

* 웹 소켓에 메시지 보내기

*/

public void sendMessage(String message) {

System.out.println("################# sendMessage : " + message);

this.userSession.getAsyncRemote().sendText(message);

}

}


2-2. TestEndpointJavaRun.java


public class TestEndpointJavaRun {


public static void main(String[] args) {

try {

// open websocket

TestEndpointClient clientEndPoint = new TestEndpointClient();

// send message

clientEndPoint.sendMessage("메세지를 첫번째로 보냅니다......");

clientEndPoint.sendMessage("메세지를 두번째로 보냅니다......");

clientEndPoint.sendMessage("메세지를 세번째로 보냅니다......");


// close websocket

clientEndPoint.onClose();


} catch (Exception e) {

e.getStackTrace();

}

}

}


3. TestEndpointJspRun.jsp (Websocket Client : jsp 테스트용 1. 서버를 띄운뒤 3. jsp에 접근해서 테스트)


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<title>Websocket Test</title>

</head>

<body>

<form>

<input id="message" type="text">

<input onclick="wsSendMessage();" value="Echo" type="button">

<input onclick="wsCloseConnection();" value="Disconnect" type="button">

</form>

<br>

<textarea id="echoText" rows="30" cols="100"></textarea>

<script type="text/javascript">

var webSocket = new WebSocket("ws://127.0.0.1:7200/websocket");

var echoText = document.getElementById("echoText");

echoText.value = "";

var message = document.getElementById("message");

webSocket.onopen = function(message){ wsOpen(message);};

webSocket.onmessage = function(message){ wsGetMessage(message);};

webSocket.onclose = function(message){ wsClose(message);};

webSocket.onerror = function(message){ wsError(message);};

function wsOpen(message){

echoText.value += "Connected ... \n";

}

function wsSendMessage(){

webSocket.send(message.value);

echoText.value += "Message sent to the server : " + message.value + "\n";

message.value = "";

}

function wsCloseConnection(){

webSocket.close();

}

function wsGetMessage(message){

echoText.value += "Message received from to the server : " + message.data + "\n";

}

function wsClose(message){

echoText.value += "Disconnect ... \n";

console.log("disconnect", message);

}


function wsError(message){

echoText.value += "Error \n";

console.log("error", message);

}

</script>

</body>

</html>






반응형

+ Recent posts