简体   繁体   中英

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.

Apache Tomcat 7 ships with an example WebSocket echo implementation.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM