javascript not firing onmessage / onopen methods for websocket connection - java

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) { }
}
}

Related

Tomcat 9 and websocket. Got a 404 error. What is wrong in my code?

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")"

browser call - Twilio.js in Struts2 (Java)

New to Struts2 and Twilio.js (api sdk) here needing guidance.
I have double checked my twilio credentials, created access token and got it accepted on my browser, "[Device]: Stream is ready" on the console log. When I try to dial a number using the Twilio.Device.connect(~), console log shows {code: 31002, message: "Connection Declined", connection: a}. I don't know what to look for on the logs. I have setup the voice URL of TwiML app on the twilio account and test connection with ngrok https.
//ACTIVATE CALL START
var connection = null;
$("#activate-calls").click(function(){
$("#answer").hide();
$("#hangup").hide();
$("#reject").hide();
$.getJSON('activateCalls').done(
function (data) {
// log('Got a token.');
console.log('Token: ' + data.data.token);
// Setup Twilio.Device
Twilio.Device.setup(data.data.token, {debug: true});
Twilio.Device.ready(function (device) {
$("#log").text("Ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
$("#call").hide();
$("#reject").hide();
$("#hangup").show();
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended. Ready for new incoming/ outgoing calls.");
$("#hangup").hide();
$("#call").show();
});
Twilio.Device.incoming(function(conn) {
// Set the reference to the current
// connection when we receive an
// incoming call
alert("ringring");
connection = conn;
$("#log").text("Incoming call from " + conn.parameters.From);
$("#answer").show();
$("#call").hide();
$("#reject").show();
// Clear the reference to the
// connection when disconnected.
connection.disconnect(function() {
connection = null;
})
});
Twilio.Device.cancel(function(conn) {
$("#log").text("Ready");
$("#answer").hide();
$("#reject").hide();
$("#call").show();
});
$("#reject").click(function() {
$("#log").text("Incoming call is rejected. Ready for new incoming/ outgoing calls.");
connection.reject();
$("#answer").hide();
$("#reject").hide();
$("#call").show();
});
$("#answer").click(function() {
// If there's no pending connection,
// there's nothing to do.
if (!connection) { return; }
// Update the interface
$("#answer").hide();
$("#call").show();
$("#log").text("Call accepted");
// Accept the current connection.
connection.accept();
});
$("#call").click(function() {
// get the phone number to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
});
$("#hangup").click(function() {
Twilio.Device.disconnectAll();
$("#log").text("Ready");
});
}
);
});
//ACTIVATE CALL END
The jsp/html looks like this..
<div align="center">
<div class="form-inline">
<div class="input-group">
<div class="input-group-addon"><img src="https://www.twilio.com/bundles/favicons/img/Twilio_16.png" /></div>
<input type="text" class="form-control" id="number" name="number">
</div>
<button class="btn btn-success" id="answer">Accept</button>
<button class="btn btn-success" id="call">Call</button>
<button class="btn btn-danger" id="hangup">Hangup</button>
<button class="btn btn-danger" id="reject">Reject</button>
</div>
<br>
<div id="log" class="alert-info" style="width: 347px; font-size: large;"></div>
</div>
My action class on activeCalls to create token is this:
public String execute(){
logger.debug("MCI> ActivateCallsAction.execute");
String identity = "johnny";
List<Scope> scopes = new ArrayList<>();
scopes.add(new IncomingClientScope(identity));
scopes.add(new OutgoingClientScope.Builder(APP_SID).build());
Jwt jwt = new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN).scopes(scopes).build();
String token = jwt.toJwt();
logger.debug("token: " + token);
HashMap<String, String> json = new HashMap<>();
json.put("identity", identity);
json.put("token", token);
data = json;
logger.debug(json.get("token") + "-" + json.get("identity"));
return "success";
}
I can post the complete error from the console logs if needed. TIA!

how to register an endpoint listener?

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"

How to handle pinging remote servers in Websockets?

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

WebSocket not working in chat application?

This is my java class
public class ServerEndPointDemo
{
#OnOpen
public void handleOpen()
{
System.out.print("Connectin is created");
}
#OnMessage
public String handleMessage(String message)
{
System.out.print("message from Client = "+message);
String replyMessage = "echo"+message;
System.out.print("message send to Client = "+replyMessage);
return replyMessage;
}
#OnClose
public void handleClose()
{
System.out.print("Connectin is closed");
}
#OnError
public void handleError(Throwable e)
{
e.printStackTrace();
}
}
This is my jsp page
<!DOCTYPE html>
<html>
<head>
<title>WEB SOCKET 01</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form>
<input type="text" name="t1" id="textMessage">
<input type="button" value="SendMessage" onclick="sendMessage()" >
</form>
<textarea rows="10" cols="20" id="messagesTextArea"></textarea>
<script type="text/javascript" language="javascript">
var messagesTextArea = document.getElementById("messagesTextArea");
var textMessage = document.getElementById("textMessage");
var webSocket = new webSocket("ws://localhost:8080/WebSocketPrj01/ServerEndPointDemo");
webSocket.Onopen = function Message(){processOpen(message);};
webSocket.Onmessage = function Message(){processMessage(message);};
webSocket.Onclose = function Message(){processClose(message);};
webSocket.Onerror = function Message(){processError(message);};
function processOpen(message)
{
messagesTextArea.value +="server Connected....."+"\n";
}
function processMessage(message)
{
messagesTextArea.value +="Receive from server....."+message.data+"\n";
}
function processClose(message)
{
webSocket.send("client disconnected");
messagesTextArea.value +="server DISConnected....."+"\n";
}
function sendMessage()
{
alert("enter");
if(textMessage.value!=="close")
{
alert(textMessage.value);
webSocket.send(textMessage.value);
alert("2");
messagesTextArea.value +="send to server....."+textMessage.value()+"\n";
alert("3");
textMessage.value="";
alert("4");
}
else{
alert("else message");
webSocket.close();
}
}
function processError(message)
{
webSocket.send("client disconnected");
messagesTextArea.value +="error....."+"\n";
}
</script>
</body>
</html>
This line is not working webSocket.send(textMessage.value);
Also I am getting this error on console while inspecting element
TypeError: webSocket is not a constructor newjsp.jsp:25.
TypeError: webSocket is undefined
It should be:
var webSocket = new WebSocket("ws://localhost:8080/WebSocketPrj01/ServerEndPointDemo");
("WebSocket" starting with capital letter).

Categories