Created
March 17, 2015 06:14
-
-
Save wmcu/aa24562760343dc61776 to your computer and use it in GitHub Desktop.
Example of Websocket on tomcat8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.simpleweb2; | |
import java.io.IOException; | |
import javax.websocket.OnClose; | |
import javax.websocket.OnMessage; | |
import javax.websocket.OnOpen; | |
import javax.websocket.Session; | |
import javax.websocket.server.ServerEndpoint; | |
/** | |
* @ServerEndpoint gives the relative name for the end point This will be | |
* accessed via ws://localhost:8080/<ProjectName>/echo Where | |
* "localhost:8080" is the address of the host, <ProjectName> is | |
* the name of the project and "echo" is the address to access | |
* this class from the server | |
*/ | |
@ServerEndpoint("/echo") | |
public class EchoServer { | |
/** | |
* @OnOpen allows us to intercept the creation of a new session. The session | |
* class allows us to send data to the user. In the method onOpen, | |
* we'll let the user know that the handshake was successful. | |
*/ | |
@OnOpen | |
public void onOpen(Session session) { | |
System.out.println(session.getId() + " has opened a connection"); | |
try { | |
session.getBasicRemote().sendText("Connection Established"); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
/** | |
* When a user sends a message to the server, this method will intercept the | |
* message and allow us to react to it. For now the message is read as a | |
* String. | |
*/ | |
@OnMessage | |
public void onMessage(String message, Session session) { | |
System.out.println("Message from " + session.getId() + ": " + message); | |
try { | |
session.getBasicRemote().sendText(message); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
/** | |
* The user closes the connection. | |
* | |
* Note: you can't send messages to the client from this method | |
*/ | |
@OnClose | |
public void onClose(Session session) { | |
System.out.println("Session " + session.getId() + " has ended"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment