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).
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"
How to config spring-websocket with 'WebApplicationInitializer':
WebAppInitializer.java
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext)throws ServletException {
AnnotationConfigWebApplicationContext SpringWebSocketContext = new AnnotationConfigWebApplicationContext();
SpringWebSocketContext.register(WebSocketConfig.class);
}
}
WebSocketConfig.java
#Configuration
#EnableWebSocketMessageBroker
#ComponentScan({ "service" })
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
GreetingController.java
#Controller
public class GreetingController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello WebSocket</title>
<script src="lib/sockjs/sockjs.min.js"></script>
<script src="lib/sockjs/stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS('/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
stompClient.disconnect();
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
when I run it,an error occurred in browser console.
Opening Web Socket... stomp.js:145
GET http://127.0.0.1:8080/hello/info 404 (Not Found) sockjs.min.js:27
Whoops! Lost connection to undefined stomp.js:145
The problem is in where you create the socket.
you should specify the contextRoot of your project
var socket = new SockJS('{contextRoot}/hello');
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 have a login form in my jsp file that is referring to a javascript function using onclick function,
The javascript function is supposed to to call an action method to do the authorization process and return the results.
Result can be a message of error (user name is wrong) or (username or password is wrong) or a success message (return "SUCCESS") to get to new page,
any time that it calls the action the alert(xmlHttp.status) shows that it receives "undefined"
it is calling a correct action but its problem is on receiving the response.
how should I define the struts.xml? maybe the problem is caused by it.
<s:submit onclick="auth(this.form)" />
xmlhttp.open("get","Login.action?usrname="+usr+"&pass="+psw,false);
xmlhttp.send();
You need to do like this (Struts2, JSON, Ajax)
struts.xml
<package name="default" extends="json-default">
<action name="ValidateUserName" class="com.controller.JSONUserAction">
<result type="json"></result>
</action>
</package>
Controller Class Code JSONUserAction.java (in your case Login.java)
package com.controller;
import com.opensymphony.xwork2.ActionSupport;
public class JSONUserAction extends ActionSupport {
private String username;
private String result;
// all struts logic here
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String execute() {
if(username.equalsIgnoreCase("admin")) {
result = "VALID";
} else {
result = "INVALID";
}
System.out.println("username : " + username + "======== result :" + result);
return ActionSupport.SUCCESS;
}
}
login.jsp code
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script type="text/javascript">
var http;
if(window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
function AuthenticateUser() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
http.open("POST", "ValidateUserName.action", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange = ValidUser;
http.send("username="+username +"&password="+password);
}
function ValidUser() {
if(http.readyState == 4 && http.status == 200) {
var jsonOP = eval ("(" + http.responseText + ")");
var result = jsonOP.result;
document.getElementById("message").innerHTML = result;
if(result == "VALID") {
//redirect to welcome page
}
}
}
</script>
</head>
<body>
<s:form action="Welcome">
<div id="message"></div>
<s:textfield name="username" label="Username" id="username" />
<s:password name="password" label="Password" id="password"/>
<s:submit id="login" onClick="AuthenticateUser();"/>
</s:form>
</body>
</html>