I have a web interface through which I can perform/apply actions on backend systems like Hadoop. I am trying to code a functionality which allows me to track the status of the server. Basically to see if the server/service is up or down. I need to do this every 2 minutes. So should I go with a Websocket or a SSE(Server Sent Event) for this..I have written this code to perform this. However the moment I code for checking the status every 2 minutes. It becomes a blocking call and I am unable to perform any other functionality of the Web UI
Following is the Code
import java.io.*;
import java.net.*;
import java.util.concurrent.TimeUnit;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class Websocket {
#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();
}
onping(session);
}
public void onping(Session session) throws IOException
{ if (session.isOpen())
{
session.getBasicRemote().sendText("In PING");
String ip = "200.168.100.46";
InetAddress inet = InetAddress.getByName(ip);
if(inet.isReachable(1000))
{
session.getBasicRemote().sendText("Alive");
}
}
else
{
System.out.println("Error");
}
}
#OnClose
public void onClose(Session session){
System.out.println("Session " +session.getId()+" has ended");
}
}
And the Client Side Code is
<!DOCTYPE html>
<html>
<head>
<title>Websocket</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div>
<input type="text" id="messageinput"/>
</div>
<div>
<button type="button" onclick="openSocket();" >Open</button>
<button type="button" onclick="closeSocket();" >Close</button>
<button type="button" onclick="pingSocket();" >Ping</button>
</div>
<!-- Server responses get written here -->
<div id="messages"></div>
<!-- Script to utilise the WebSocket -->
<script type="text/javascript">
var webSocket;
var messages = document.getElementById("messages");
function openSocket(){
// Ensures only one connection is open at a time
if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
writeResponse("WebSocket is already opened.");
return;
}
// Create a new instance of the websocket
webSocket = new WebSocket("ws://localhost:8080/Websocket/echo");
/**
* Binds functions to the listeners for the websocket.
*/
webSocket.onopen = function(event){
// For reasons I can't determine, onopen gets called twice
// and the first time event.data is undefined.
// Leave a comment if you know the answer.
if(event.data === undefined)
return;
writeResponse(event.data);
};
webSocket.onmessage = function(event){
writeResponse(event.data);
};
webSocket.onclose = function(event){
writeResponse("Connection closed");
};
}
/**
* Sends the value of the text input to the server
*/
function send(){
var text = document.getElementById("messageinput").value;
webSocket.send(text);
}
function pingSocket(){
var text = document.getElementById("messageinput").value;
webSocket.send("PING");
}
function closeSocket(){
var text = document.getElementById("messageinput").value;
webSocket.send(text);
webSocket.close();
}
function writeResponse(text){
messages.innerHTML += "<br/>" + text;
}
</script>
</body>
</html>
So can you let me know what am i doing wrong?
Thanks
Related
I'm t rying to make my the first simple client-servet application with web socket and tomcat 9 server. I found this example in the enternet. I had the next error:
(index):17 WebSocket connection to 'ws://localhost:8080/JavaWebSocket/ws' failed:
Error during WebSocket handshake: Unexpected response code: 404"
it's this line:
var webSocket = new WebSocket("ws://localhost:8080/JavaWebSocket/ws")"
I thought the initialisation should be
var webSocket = new WebSocket("ws://localhost:8080/[nameOfTheClassWithWebSocket]/ws");
But it doesn't work too :( I tried everything :( I can't solve this problem :(
Java code and Jsp file with project scheme are bellow.
Java code:
package socket;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/ws")
public class WebSocketServerExample {
#OnOpen
public void onOpen(){
System.out.println("Open Connection ...");
}
#OnClose
public void onClose(){
System.out.println("Close Connection ...");
}
#OnMessage
public String onMessage(String message){
System.out.println("Message from the client: " + message);
String echoMsg = "Echo from the server : " + message;
return echoMsg;
}
#OnError
public void onError(Throwable e){
e.printStackTrace();
}
}
jsp file:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Tomcat WebSocket</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="5" cols="30"></textarea>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/JavaWebSocket/ws");
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){ console.log(message);};
webSocket.onerror = function(message){ console.log(message);};
function wsOpen(message){
echoText.value += "Connected ... \n";
}
function wsSendMessage(){
webSocket.send(message.value);
echoText.value += "Message sended 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";
}
function wserror(message){
echoText.value += "Error ... \n";
}
</script>
</body>
</html>
Scheme of the Project
Your url will be
var webSocket = new WebSocket("ws://localhost:[port]/appcontext/ws")"
i am using grails 3.0.9 , use javax.websocket to create a chatting application.
this is my code...
`
import grails.util.Environment
import javax.servlet.ServletContext
import javax.servlet.ServletContextEvent
import javax.servlet.ServletContextListener
import javax.websocket.server.ServerEndpoint
import javax.websocket.server.ServerContainer
import javax.websocket.OnMessage
import javax.websocket.OnOpen
import javax.websocket.OnClose
import javax.websocket.OnError
import javax.servlet.annotation.WebListener
#WebListener
#ServerEndpoint("/chatEndPoint")
class ServerEndPointDemo implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.servletContext
final ServerContainer serverContainer = servletContext.getAttribute("javax.websocket.server.ServerContainer")
try {
if (Environment.current == Environment.DEVELOPMENT) {
serverContainer.addEndpoint(ServerEndPointDemo)
}
println "--- we have a connection"
int defaultMaxSessionIdleTimeout = 0 //config.timeout ?: 0
serverContainer.defaultMaxSessionIdleTimeout = defaultMaxSessionIdleTimeout
}
catch (IOException e) {
log.error e.message, e
}
}
#Override
public void contextDestroyed(ServletCo
ntextEvent event) {
}
#OnOpen
public void handleOpen(){
println "is connecting"
}
#OnClose
public void handleClose(){
println "closed lah!"
}
#OnMessage
public String handleMessage(String message){
println "receiveed message from client = "+message
return "my message~"
}
#OnError
public void handleError(Throwable t){
println "error ~"
}
}
this is my controller..
chatController.groovy
package com.akiong.maintenance
class ChatController {
def index() {
}
}
this is my gsp
index.gsp
<html>
<head>
<title>Chatting</title>
<script language="javascript" type="text/javascript">
var websocket;
function init() {
output = document.getElementById("output");
}
function send_echo() {
var wsUri = "ws://localhost:8080/chatEndPoint";
writeToScreen("Connecting to " + wsUri);
websocket= new WebSocket(wsUri);
websocket.onopen = function (evt) {
writeToScreen("Connected !");
doSend(textID.value);
};
websocket.onmessage = function (evt) {
writeToScreen("Received message: " + evt.data);
websocket.close();
};
websocket.onerror = function (evt) {
writeToScreen('<span style="color: red;">ERROR:</span> '
+ evt.data);
websocket.close();
};
}
function showErrorInfo(e) {
alert('Error connecting socket'+e);
}
function doSend(message) {
websocket.send(message);
writeToScreen("Sent message: " + 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);
</script>
</head>
<body>
<h1>Echo Server</h1>
<div style="text-align: left;">
<form action="">
<input onclick="send_echo()" value="Press to send"
type="button">
<input id="textID" name="message" value="Hello Web Sockets"
type="text">
<br>
</form>
</div>
<div id="output"></div>
</body>
</html>
i have no idea..i cannot connect to endpoint...
i already read this question grails javax.websocket issues
but im using grails 3.0.9, its look like diferent because under grails 3.0.9 havenot a folder with "scripts"
I am trying to implement HTML5 web socket using Netbeans and Apache server..
the implementation is working fine in my laptop but when i am trying to access the same program on other machines connected in LAN using IP address ...i get the error "connection closed" in other machine.
here is my index.html file :
<!DOCTYPE html>
<html>
<head>
<title>Echo Chamber</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<center>
<div>
<input type="text" id="messageinput"/>
</div>
<br>
<div>
<button type="button" onclick="openSocket();" >Open</button>
<button type="button" onclick="send();" >Send</button>
<button type="button" onclick="closeSocket();" >Close</button>
</div>
<br>
<hr>
<br>
<!-- Server responses get written here -->
<div id="messages"></div>
</center>
<!-- Script to utilise the WebSocket -->
<script type="text/javascript">
var webSocket;
var messages = document.getElementById("messages");
function openSocket(){
// Ensures only one connection is open at a time
if(webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED){
writeResponse("WebSocket is already opened.");
return;
}
// Create a new instance of the websocket
webSocket = new WebSocket("ws://localhost:8080/HTML_5_Socket_Appache/echo");
/**
* Binds functions to the listeners for the websocket.
*/
webSocket.onopen = function(event){
// For reasons I can't determine, onopen gets called twice
// and the first time event.data is undefined.
// Leave a comment if you know the answer.
if(event.data === undefined)
return;
writeResponse(event.data);
};
webSocket.onmessage = function(event){
writeResponse(event.data);
};
webSocket.onclose = function(event){
writeResponse("Connection closed");
};
}
/**
* Sends the value of the text input to the server
*/
function send(){
var text = document.getElementById("messageinput").value;
webSocket.send(text);
}
function closeSocket(){
webSocket.close();
}
function writeResponse(text){
messages.innerHTML += "<br/>" + text;
}
</script>
</body>
</html>
and here is my java file :
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/EchoChamber/echo
* Where "localhost" is the address of the host,
* "EchoChamber" is the name of the package
* 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");
} }
please help me as to where i am getting wrong which prevents the code to run only in my machine and no other machines connected in the network.
The problem here is with Origin verification - you need to set your server to actually serve the (static) html page - not just deployed websocket endpoint.After that, Origin header will be added with the same host (by browser runtime) and everything should work as expected.
You should use something similar to [how to construct a websocket uri relate to the page uri], which would let you use relative uri for your websocket endpoint (compared to hardcoded value you have now).
I am trying to follow the instructions given in this tutorial and create a sample application in Netbeans. I have reached till the testing part. When I run the application in chrome it says
WebSocket connection to
'ws://localhost:8080/WhiteboardApp/whiteboardendpoint' failed: Error
during WebSocket handshake: Unexpected response code: 404
index.html
<!DOCTYPE html>
<html>
<head>
<title>Start Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Collaborative Whiteboard App</h1>
<div id="output"></div>
<script type="text/javascript" src="websocket.js"></script>
</body>
</html>
websocket.js
var wsUri = "ws://" + document.location.host + document.location.pathname + "whiteboardendpoint";
var websocket = new WebSocket(wsUri);
websocket.onerror = function(evt) { onError(evt) };
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
// For testing purposes
var output = document.getElementById("output");
websocket.onopen = function(evt) { onOpen(evt) };
function writeToScreen(message) {
output.innerHTML += message + "<br>";
}
function onOpen(evt) {
writeToScreen("Connected to " + wsUri);
}
// End test functions
MyWhiteboard.java
package org.myapps.whiteboardapp;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/whiteboardendpoint ")
public class MyWhiteboard {
private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());
#OnMessage
public String onMessage(String message) {
return null;
}
#OnOpen
public void onOpen (Session peer) {
peers.add(peer);
}
#OnClose
public void onClose (Session peer) {
peers.remove(peer);
}
}
Where have I gone wrong ? How can I solve this problem ?
You have an invalid server annotation
Fix this
#ServerEndpoint("/whiteboardendpoint ")
To
#ServerEndpoint("/whiteboardendpoint") /* removed space */
The way you have it defined currently, you could probably just change your javascript wsUri definition to ...
var wsUri = "ws://" + document.location.host + document.location.pathname +
"whiteboardendpoint%20";
var websocket = new WebSocket(wsUri);
and have it work. (just added a URI encoded space)
I am trying to implement a basic server client communication through web sockets. I have console prints in my server to tell me when a conection opeened and when a message is recieved. As soon as i press send button on my client, i get an "something recieved" console print from the server but the onopen function of client (pasted below) is not fired. Same happens with other functions as well. What am i doing wrong ?
Here is my code :
Client Side code for html age:
<script type="text/javascript">
document.getElementById("msg").value = "Website Opened";
var ws = new WebSocket("ws://localhost:8080/PushServlet/echo");
ws.onopen = function ()
{
document.getElementById("msgArea").textContent += "Connection Opened \n";
};
function connect()
{
ws = new WebSocket("ws://localhost:8080/PushServlet/echo");
var wss = "ws = " + ws.toString();
document.getElementById("msgArea").textContent += wss;
};
ws.onmessage = function(message)
{
document.getElementById("msgArea").textContent += message.data;
};
function postToServer()
{
if(ws == null)
{
document.getElementById("msgArea").textContent += "Connection Null \n";
}
ws.send(document.getElementById("msg").value);
document.getElementById("msg").value = "";
};
ws.onclose = function(evt)
{
document.getElementById("msgArea").textContent += "closed";
};
function updateTextBox()
{
document.getElementById("msg").value = "Blah Blah Blah";
};
function closeConnect()
{
document.getElementById("msg").value = "Blah Blah Blah";
ws.close();
};
</script>
</head>
<body>
<div>
<textarea rows="4" cols="100" id="msgArea" readonly></textarea>
</div>
<div>
<input id="msg" type="text" value="Website Opened 1" />
<button type="submit" id="sendButton" onclick="postToServer()">Send</button>
<button type="submit" id="update_button" onclick="connect()" > Update </button>
</div>
</body>
</html>
Server Side code for websocket connection:
package com.servlet.pushServlet;
import java.io.IOException;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoEndpoint {
#OnMessage
public void onMessage(Session session, String msg) {
try {
session.getBasicRemote().sendText("Send something");
System.out.println("Some thing recieved");
session.close();
} catch (IOException e) { }
}
}