나는 지금 Websocket을 탐험 중이다. 나는 몇 가지 설명이 필요하다. 나는 바람둥이와 함께 websocket을 사용하고있다.websocket에 대한 설명
tomcat이 webSocket 요청을 특정 Java 클래스에 매핑하는 방법. 예를 들어 web.xml에 서블릿 클래스를 제공 할 수 있습니다. 그러나 websocket에서 어떻게 작동합니까?
나는 지금 Websocket을 탐험 중이다. 나는 몇 가지 설명이 필요하다. 나는 바람둥이와 함께 websocket을 사용하고있다.websocket에 대한 설명
tomcat이 webSocket 요청을 특정 Java 클래스에 매핑하는 방법. 예를 들어 web.xml에 서블릿 클래스를 제공 할 수 있습니다. 그러나 websocket에서 어떻게 작동합니까?
1- 자바 스크립트 : websocket의 변수를 다음과 같이 선언하십시오. var websocket; var address = "ws : // localhost : 8080/appName/MyServ";
통지 프로그램 응용 응용 프로그램의 이름이고 MyServ는 엔드 포인트도
스크립트에 연결 열 수있는 기능을 추가하는 것을 : 서버 측에서
var websocket;
var address = "ws://localhost:8080/appName/MyServ";
function openWS() {
websocket = new WebSocket(address);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
websocket.onclose = function(evt) {
onClose(evt)
};
}
function onOpen(evt) {
// what will happen after opening the websocket
}
function onClose(evt) {
alert("closed")
}
function onMessage(evt) {
// what do you want to do when the client receive the message?
alert(evt.data);
}
function onError(evt) {
alert("err!")
}
function SendIt(message) {
// call this function to send a msg
websocket.send(message);
}
2를, 당신은 ServerEndpoint 필요 : 위의 스크립트에서 myServ라고 부릅니다. @ServerEndpoint으로 주석에 의해 모든 Java POJO 클래스 웹 소켓 서버 엔드 포인트를 선언
import java.io.IOException
import javax.servlet.ServletContext;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value="/MyServ")
public class MyServ{
@OnMessage
public void onMessage(Session session, String msg) throws IOException {
// todo when client send msg
// tell the client that you received the message!
try {
session.getBasicRemote().sendText("I got your message :"+ msg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnOpen
public void onOpen (Session session) {
// tell the client the connection is open!
try {
session.getBasicRemote().sendText("it is open!");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnClose
public void onClose (Session session) {
System.out.println("websocket closed");
}
@OnError
public void onError (Session session){
}
}
이 괜찮습니다 :)하지만 어떻게이 WS 요청 범위를 :
지금, 나는 이것이 당신이 필요로 정확히 생각 그 목적지? 바람둥이가 그것을 어떻게 처리 했습니까? –
이것은 클라이언트 측에서 연결을 여는 것입니다. websocket = new WebSocket ("ws : // localhost : 8080/appName/MyServ"); 다음 서버 측에 ServerEndpoint, @ServerEndpoint (value = "/ MyServ")가 있습니다. Tomcat은 헤더를 요청하고 일치하는 URI를 찾습니다. 이것 좀 봐 http://stackoverflow.com/questions/26103939/how-tomcat-8-handles-websocket-upgrade-request – MedoMe