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)
Related
My problem comes when I try to implement SockJS on Java Vertx with a simple broadcast message example , I only get the "Welcome to SockJS message!" on the server side, but the frontend and the backend do not seem to be connecting. I am new to Vertx and SockJS, so any help will be very much appreciated.
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Push Notifications</title>
<script src="client.js"> </script>
<script src="https://unpkg.io/sockjs-client#1.5.0/dist/sockjs.min.js"></script>
</head>
<body>
<h1>Push Notifications With Vertx</h1>
<script>
var sock;
function openSock() {
sock = new SockJS('http://localhost:8080/myapp');
sock.onopen = function() {
sock.onopen = function() {
console.log('open');
};
sock.onmessage = function(e) {
console.log('message', e.data);
};
sock.onevent = function(event, message) {
console.log('event: %o, message:%o', event, message);
return true; // in order to signal that the message has been processed
};
sock.onerror = function(e) {
console.error(e);
}
sock.onunhandled = function(json) {
console.log('this message has no address:', json);
};
sock.onclose = function() {
console.log('close');
};
sock.send('test');
}
}
openSock();
</script>
</body>
</html>
and here is my MainVerticle.java
package com.bcm.vertxmvn;
import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MainVerticle extends AbstractVerticle {
private static final Logger LOGGER = LoggerFactory.getLogger(MainVerticle.class);
#Override
public void start() {
Router router = Router.router(vertx);
SockJSHandlerOptions options = new SockJSHandlerOptions()
.setHeartbeatInterval(2000);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
router.mountSubRouter("/myapp", sockJSHandler.socketHandler(sockJSSocket -> {
// Just echo the data back
sockJSSocket.handler(sockJSSocket::write);
}));
vertx.createHttpServer().requestHandler(router).listen(8080);
}
}
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 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
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).
i'm new in a web service. i'm trying to make a simple web service REST on java for a simple login application.. here's my code:
Server side:
package com.testingws.webservices;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/login/{username}/{password}/{datetime}")
public class webServicesClass {
#GET // this method process GET request from client
#Produces("application/json") // sends JSON
public String getJson( #PathParam("username") String username, #PathParam("password") String password) { // empno represents the empno sent from client
if (username.equalsIgnoreCase("admin") && password.equalsIgnoreCase("admin")){
return "{'loginstatus':'success'}";
}
else{
return "{'loginstatus':'failed'}";
}
} // end of
}
Client side :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Client Login</title>
<script type="text/javascript">
function loginProcess(){
var tempUser = document.getElementById("loginUsername");
var tempPass = document.getElementById("loginPassword");
var dateTime = new Date();
var url = "http://localhost:8181/TestWSProject/authentication/login/" + tempUser.value + "/" + tempPass.value + "/" + dateTime.toUTCString();
var xmlhttp = new XMLHttpRequest(); //#slaks: i put it here
xmlhttp.open('GET',url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if ( xmlhttp.status == 200) {
var det = eval( "(" + xmlhttp.responseText + ")");
//alert(det.loginstatus);
if(det.loginstatus=="success")
{
setCookie("login", "yes", 1);
window.location="main.html";
}
else
{
alert("incorrect username or password");
}
}
else
alert("Error ->" + xmlhttp.status + xmlhttp.responseText);
}
}
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var loginStatus=getCookie("login");
//alert(loginStatus);
if (loginStatus=="yes")
{
//alert("Masuk pengecekan")
window.location="main.html";
}
}
</script>
</head>
<body onload="checkCookie()">
<h2>LOGIN FORM</h2>
<BR>
Username : <input type="text" id="loginUsername"/>
<BR>
Password : <input type="password" id="loginPassword"/>
<BR>
<input type="button" value="Login" onclick="loginProcess()"/>
</body>
</html>
when i access my client from webContent url (http://localhost/TestWSProject/index.html) that service works perfectly, but if i access my client from stand alone HTML file (file:///D:/+Prog/webservice/TestWSProject/WebContent/index.html) it give me xmlHTTPStatus = 0 and that service is not works.. any solution for this problem?? really thanks..
Some browsers have security restrictions which restrict files from performing certain actions if they are being accessed directly from the file system.
This could be what is causing the error.