Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Tomcat websockets implementation on localhost

I am trying to learn websockets. Tried a few examples given on apache tomcat 7 websockets examples -> 'http://tomcat.apache.org/tomcat-7.0-doc/web-socket-howto.html'. I'm done with the client-side code. having a problem with the server-side one which is to be written in a java servlet. I tried to run the examples on my localhost using eclipse and Apache Tomcat 7.0.52. Can anyone help me with some tutorials and examples for the server code.

Here is the client side code for a simple echo server:

var wsUri = "ws://echo.websocket.org/"; 
var output; 

function init() { 
output = document.getElementById("output");
$('‪#‎send‬').click(function(){
doSend("ja ghari");
});
testWebSocket(); } 

function testWebSocket() {
websocket = new WebSocket(wsUri); 
websocket.onopen = function(evt) { onOpen(evt);};
websocket.onclose = function(evt) { onClose(evt) ;}; 
websocket.onmessage = function(evt) { onMessage(evt) ;}; 
websocket.onerror = function(evt) { onError(evt) ;}; } 

function onOpen(evt) { 
writeToScreen("CONNECTED"); 
doSend("WebSocket rocks");
} 

function onClose(evt) { 
writeToScreen("DISCONNECTED"); } 

function onMessage(evt) { 
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); 
} 

function onError(evt) { 
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); } 

function doSend(message) { 
writeToScreen("SENT: " + message); 
websocket.send(message); } 

function writeToScreen(message) { 
var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; 
pre.innerHTML = message; output.appendChild(pre); } 

window.addEventListener("load", init, false); 

now i need to write a server side code in java for this I need a server which will communicate with my client using websockets

Apache Tomcat 7 or above is a must, server side code to be written in java. Thanks in advance.

like image 896
Padfoot Avatar asked Dec 16 '22 00:12

Padfoot


1 Answers

Apache Tomcat 7 ships with an example WebSocket echo implementation.

  • Client side code
  • Server side code using annotations
  • Server side code without annotations

You don't write the server side as a Servlet. You need to implement a WebSocket endpoint. Tomcat will handle the plumbing to route the request to the endpoint.

like image 161
Mark Thomas Avatar answered Dec 28 '22 22:12

Mark Thomas