WebSocket Programming in Java: client server communication issue - java

I am trying to implement simple WebSocket program using Java Web Application.
However, not able to establish communication between client and server.
Can anybody help me?
Web Server: Tomcat
client code: jsp/javascrip
<body>
<div>
<input type="text" value="" id="message" /> <br /> <input
type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket;
var uri = 'ws://' + window.location.host + '/ZebraHosting/testwebsocket';
alert('ur url is ' + uri);
function connect() {
if ('WebSocket' in window) {
alert('I am in Websocket in window');
websocket = new WebSocket(uri);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket(uri);
alert('I am in MozWebsocket in window');
} else {
alert('WebSocket is not supported by this browser.');
return;
}
webSocket.onerror = function(event) {
alert('I am onerror');
onError(event);
};
webSocket.onopen = function(event) {
alert('I am onopen');
onOpen(event);
};
webSocket.onmessage = function(event) {
alert('I am onmessage');
onMessage(event);
};
webSocket.onclose = function(event) {
alert('I am onclose');
onClose(event);
};
}
function onMessage(event) {
document.getElementById('messages').innerHTML += '<br />'
+ event.data;
}
function onOpen(event) {
alert("function onOpen " );
document.getElementById('messages').innerHTML = 'Connection established';
}
function onError(event) {
alert("Error ocurred " );
}
function start() {
alert("function start " );
webSocket.send(document.getElementById('message').value);
return false;
}
function onClose(event) {
alert("function onClose" );
document.getElementById('messages').innerHTML = 'Connection closed';
}
connect();
</script>
Server Code:
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("/testwebsocket")
public class WebSocketTest {
#OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
// Print the client message for testing purposes
System.out.println("Received: " + message);
// Send the first message to the client
session.getBasicRemote().sendText("replay from server for :" + message);
}
#OnOpen
public void onOpen() {
System.out.println("Client connected");
}
#OnClose
public void onClose() {
System.out.println("Connection closed");
}}

You have typos in your code: You create WebSocket objects and assign it to variable websocket but later use variable webSocket.

I think #ApplicationScoped annotation is missing for server side class.
See this tutorial http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

Related

socketio.emit doesn't work netty socketio

I'm working with socketio and netty with java and I'm new to both of them.
my client side code looks like this.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title >webSocket test</title>
<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
< !-- New Bootstrap core CSS file-->
<!-- Optional Bootstrap theme file (generally not necessary to import) -->
<!- -jQuery file. Be sure to introduce before bootstrap.min.js -->
<!-- The latest Bootstrap core JavaScript file-->
<script type=" text/javascript">
$(function(){
/**
* The socket.emit("event name", "parameter data") method of the
front-end js is used when triggering the back-end custom message event, * front-end js The socket.on("event name", anonymous function (data sent by the server to the client)) for monitoring server-side events
**/
//io({path: 'ws://localhost:9099/', transports: ['websocket'] ,upgrade: false});
var socket = io.connect("ws://localhost:9099",{transports: ['websocket'] ,upgrade: false});
var firstconnect = true;
if(firstconnect) {
console.log("First connection initialization");
//Monitor server connection event
socket.on('connect',function(){
socket.emit('messageEvent', 'Hello server');
console.log("First connection success");
$("#tou").html("Connect to the server successfully!");
});
//Monitor server shutdown service event
socket.on('disconnect', function(){
$("#tou").html("Disconnected from the server!");
});
//Monitor server Send message event
socket.on('responseEvent', function(data) {
console.log('data');
$("#msg").html($("#msg").html() + "<br/>" + data);
} );
firstconnect = false;
} else {
console.log("why?");
socket.socket.reconnect();
}
$('#send').bind('click', function() {
send();
});
function send(){
if (socket != null) {
var message = document.getElementById('message').value;
var title = "message";
var obj = {message:message,title:title};
var str = JSON.stringify(obj);
socket.emit("messageEvent",str);
console.log("message event" , str);
} else {
alert('Send');
}
}
});
</script>
</head>
<body>
<div class="page-header" id="tou">
webSocket Demo
</div>
<div class="well" id="msg">
</div>
<div class="col-lg">
<div class="input-group">
<input type="text" class="form-control" placeholder="send Message..." id="message">
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="send" >send</button>
</span>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row --><br><br>
</body>
</html>
The event handler is as shown below.
#Component
public class MessageEventHandler {
private static final Logger logger = LoggerFactory.getLogger(MessageEventHandler.class);
public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>();
#Autowired
private RedissonClient redisson;
#Resource
private SocketIOServer socketIOServer;
#OnConnect
public void onConnect(SocketIOClient client){
Map<String,Object> clientMap = new HashMap<>(16);
client.sendEvent("responseEvent", client.getSessionId().toString()+": "+ "hello");
if(client!=null){
String room = client.getHandshakeData().getSingleUrlParam("room");
String nameSpace = client.getNamespace().getName();
logger.info("namespace {} ",nameSpace);
String sessionId = client.getSessionId().toString();
logger.info("namespace, room={}, sessionId={},namespace={}",room,sessionId,nameSpace);
if(StringUtils.isEmpty(room)){
//client.joinRoom(room);
clientMap.put("rooms",room);
}
clientMap.put("createTime", LocalDateTime.now().toString());
redisson.getBucket("room"+sessionId).trySet(clientMap);
}
return;
}
/**
* Triggered when the client closes the connection
*
* #param client
*/
#OnDisconnect
public void onDisconnect(SocketIOClient client) {
logger.info("client:" + client.getSessionId() + "disconnected");
}
/**
* Client events
*
* #param client  
* #param request
* #param msg  
*/
#OnEvent(value = "messageEvent")
public void onMessageEvent(SocketIOClient client, AckRequest request, String msg) {
System.out.println("haha");
logger.info("message :" + msg);
//Post the message back
JSONObject jsonObject = JSON.parseObject(msg);
String message = jsonObject.getString("message");
Collection<SocketIOClient> clients = socketIOServer.getBroadcastOperations().getClients();
for (SocketIOClient clientByRoom : clients) {
clientByRoom.sendEvent("responseEvent", client.getSessionId().toString()+": "+message);
}
}
}
The server starter code is shown below.
#Component
#Order(1)
public class SocketServerRunner implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(SocketServerRunner.class);
#Resource
private SocketIOServer socketIOServer;
#Resource
private PubSubStore pubSubStore;
#Autowired
private RedissonClient redisson;
#Override
public void run(String... args) throws Exception {
logger.info("socketIOServer ");
socketIOServer.start();
pubSubStore.subscribe(PubSubType.DISPATCH, data -> {
Collection<SocketIOClient> clients = null;
String room = data.getRoom();
String namespace = data.getNamespace();
Packet packet = data.getPacket();
String jsonData = packet.getData();
if(!StringUtils.isEmpty(namespace)){
SocketIONamespace socketIONamespace = socketIOServer.getNamespace(namespace);
if(StringUtils.isEmpty(room)){
clients = socketIONamespace.getRoomOperations(room).getClients();
}
}else{
clients = socketIOServer.getBroadcastOperations().getClients();
}
if(!CollectionUtils.isEmpty(clients)){
for (SocketIOClient client : clients) {
client.sendEvent("messageEvent",jsonData);
}
}
}, DispatchMessage.class);
// addNameSpace(socketIOServer);
}
I'm getting a connection registration on the OnConnect annoted method, but the method seems to run two times cause I get the log twice while the socket connects. I don't know why it happens.
But even worse is the emit method doesn't work that is written in client side javascript. There is no error. The log below the emit is executed. But the OnEvent annoted method in the java EventHandler doesn't seem to detect it.
Can someone help me understand this?
Apparently it seems the problem is with the libraries. There is some compatibility issue with newer versions of socketio client library with netty dependencies for java and it is causing the weird problems.
My dependency for netty socketio is shown below which obviously is the latest as of answering this question.
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.19</version>
</dependency>
And for the client library to work smoothly I had to downgrade the library from 3.X.X to 2.X.X .
In my case from
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>
to
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>

ORIGINAL EXCEPTION: ReferenceError: io is not defined

I am trying to create a chat app using Ionic2 (Angular2). I have a Java Server and Ionic 2 Client.
I get the following error:
ORIGINAL EXCEPTION: ReferenceError: io is not defined
Any suggestions please?
Client
import { Component, NgZone } from '#angular/core';
import { Http } from "#angular/http";
declare var io;
//require ('io');
#Component({
templateUrl: 'build/pages/chat/chat.html',
})
export class ChatPage {
private socketHost: string = "http://localhost:3700";
private messages: string[] = [];
private zone: NgZone = null;
private chatBox: string = null;
private socket: any = null;
constructor(http: Http) {
this.messages = [];
this.zone = new NgZone({ enableLongStackTrace: false });
//let url = this.socketHost + "/fetch";
let url = this.socketHost;
http.get(url).subscribe((success) => {
var data = success.json();
for (var i = 0; i < data.length; i++) {
this.messages.push(data[i].message);
}
}, (error) => {
console.log(JSON.stringify(error));
});
this.chatBox = "";
this.socket = io(this.socketHost);
this.socket.on("chat_message", (msg) => {
this.zone.run(() => {
this.messages.push(msg);
});
});
}
send(message) {
if (message && message != "") {
this.socket.emit("chat_message", message);
}
this.chatBox = "";
}
}
HTML
<ion-navbar *navbar>
<ion-title>
Chat
</ion-title>
</ion-navbar>
<ion-content class="home">
<ion-list>
<ion-item *ngFor="let message of messages">{{message}}</ion-item>
</ion-list>
</ion-content>
<ion-footer-bar>
<ion-input>
<input type="text" [(ngModel)]="chatBox" placeholder="Message..." />
<button (click)="send(chatBox)">Send</button>
</ion-input>
</ion-footer-bar>
index.html
<script src="/socket.io/socket.io.js"></script>
Server
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
public class Server {
public static void main(String[] args) {
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(3700);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(new ConnectListener() {
#Override
public void onConnect(SocketIOClient client) {
System.out.println("onConnected");
client.sendEvent("message", new Message("", "Welcome to the chat!"));
}
});
server.addDisconnectListener(new DisconnectListener() {
#Override
public void onDisconnect(SocketIOClient client) {
System.out.println("onDisconnected");
}
});
server.addEventListener("send", Message.class, new DataListener<Message>() {
#Override
public void onData(SocketIOClient client, Message data, AckRequest ackSender) throws Exception {
System.out.println("onSend: " + data.toString());
server.getBroadcastOperations().sendEvent("message", data);
}
});
System.out.println("Starting server...");
server.start();
System.out.println("Server started");
}
}
UPDATE
I add the following to index.html, and I don't get any errors any more:
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
But it just hangs. And in Firebug, I can see that the following request is just hanging:
GET http://localhost:3700/
The following is printed in the server console:
onConnected
When the server is not running the following request times out as expected, but when the server is running, the request does return, but with a null response:
GET http://localhost:3700/socket.io/?EIO=3&transport=...LRQn9sx&sid=53081e79-81f3-4fc0-8fb7-17c8673938ca
200 OK
27ms
So it suggests that my server code or the communication between client and server is wrong I think.
Any ideas?
In your Angular app you're listening for and emitting chat_message.
In your Java server you're listening for send and emitting message.
This doesn't add up, does it?

Spring Websockets Error creating bean messageBrokerSockJsScheduler

I'm attempting to write a very basic websocket example but have ran into an issue I can't get past. I have included the exception that gets thrown at initialization as well as my code. Any help would be greatly appreciated. Thanks.
spring 4.1.1
jackson 2.1.0
servlet-api 6.0.36
JDK 1.6
Exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageBrokerSockJsScheduler': Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'removeOnCancelPolicy' of bean class
Controller:
package com.example.pocProject.controller;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class WebSocketController {
#MessageMapping("/add")
#SendTo("/topic/showResult")
public int addNum(int input1, int input2) throws Exception {
Thread.sleep(2000);
int result = input1 + input2;
return result;
}
#RequestMapping("/start")
public String start() {
return "addPage";
}
}
Websocket Config in app-Context-servlet.xml
<websocket:message-broker application-destination-prefix="/calcApp">
<websocket:stomp-endpoint path="/add">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
JavaScript:
<script type="text/javascript" src="<c:url value="/static/script/sockjs-0.3.4.js"/>"></script>
<script type="text/javascript" src="<c:url value="/static/script/stomp.js"/>"></script>
<script type="text/javascript">
var stompClient = null;
function websocketCall() {
var num1 = 5;
var num2 = 7;
connect();
stompClient.send("/pocProject/add", {}, '');
disconnect();
}
function connect() {
var socket = new SockJS('/pocProject/add');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/showResult', function(calResult) {
showResult(JSON.parse(calResult.body).result);
});
});
}
function disconnect() {
stompClient.disconnect();
console.log("Disconnected");
}
function showResult(message) {
var response = document.getElementById('calResponse');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>

Websocket evnt.data undefined after refresh

I am using websocket for showing real time message updates from the server.
My server code snippet is :
My server keeps sending string to my client till the connection is open.
#OnMessage
public void onMessage(String message, #PathParam("client-id") String clientId) {
for (Session client : clients) {
while (client.isOpen()) {
client.getAsyncRemote().sendObject(getStatus());
}
}
}
#OnClose
void onClose(Session peer) {
System.out.println("Removed Peers");
clients.remove(peer);
}
The getStatus() function returns a comma separated string.
My client receives the string(comma separated string) and keeps calling setData() which sets the html element the value of this string.
My client side code is :
var websocket;
var rows;
var vM;
function connect() {
if ($.browser.mozilla) {
webSocket = new MozWebSocket(URL);
} else {
webSocket = new WebSocket(URL);
}
websocket.onopen = function(evnt) {
onOpen(evnt);
};
websocket.onmessage = function(evnt) {
onMessage(evnt);
};
websocket.onerror = function(evnt) {
onError(evnt);
};
websocket.onclose = function() {
console.log("Disconnected");
};
displayMigration();
}
function onOpen(evnt) {
setInterval(function() {
if (websocket.bufferedAmount === 0) {
websocket.send("connect");
}
}, 600);
}
function onMessage(evnt) {
if (typeof evnt.data === "string") {
setData(evnt);
startDataUpdation();
console.log(evnt.data);
}
}
function onError(evnt) {
alert('ERROR: ' + evnt.data);
}
}
Now my websocket executes as required till the time i refresh the screen.Once I refresh it the evnt.data is undefined so onMessage is not getting called even if the connection is open and in readyState=1.
Same behavior is reflected across different browsers. I am using glassfish server 4.0 in Netbeans 7.4 j2ee.
Also after refresh I get this error in the console:
The connection to ws://localhost:8080/WebSocketWorking_2/websocket/client-id was interrupted while the page was loading.

how to run java on website and to get values to html

i know the question may sound easy to most of you but I am stuck with it.
First of all i like to define what i am trying to achieve.
on eclipse i am running a piece of code that sends some data over specific port, and via html and javascript i am getting those that it's sent and print them on screen.
I have an account from one of free hosting websites.
I want to run my code on that website e.g mywebsite.blahblah.com/...
and from html file on my computer i want to access that website, get those values produced by java code and print them on screen.
I have no idea where to start.
the codes are
java and html
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class GPSServer extends WebSocketServer {
static int port = 9876;
public GPSServer(int port) throws UnknownHostException {
super(new InetSocketAddress(port));
}
public GPSServer(InetSocketAddress address) {
super(address);
}
public void sendData(String s) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(s);
}
}
}
#Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
System.out.println(arg0.getRemoteSocketAddress().getAddress()
.getHostAddress()
+ " connected to the server!");
}
#Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
System.out.println(arg0 + " disconnected!");
}
#Override
public void onError(WebSocket arg0, Exception arg1) {
arg1.printStackTrace();
if (arg0 != null) {
}
}
#Override
public void onMessage(WebSocket arg0, String arg1) {
System.out.println(arg0 + ": " + arg1);
}
public static Runnable sendData() {
Runnable r = new Runnable() {
#Override
public void run() {
WebSocketImpl.DEBUG = true;
GPSServer server;
try {
server = new GPSServer(GPSServer.port);
server.start();
System.out.println("GPS server started at port: "
+ server.getPort());
double longitude = 39.55;
double latitude = 22.16;
String lng = Double.toString(longitude);
String ltd = Double.toString(latitude);
String all = lng + "-" + ltd;
while (true) {
server.sendData(all);
/*
* server.sendData(Double.toString(longitude));
* System.out.println("longitude sent...");
* server.sendData(Double.toString(latitude));
* System.out.println("latitude sent...");
*/
Thread.sleep(5000);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
return r;
}
public static void main(String[] args) throws UnknownHostException {
Thread thread = new Thread(GPSServer.sendData());
thread.start();
}
}
--
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
var lat;
var lng;
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9876/echo");
ws.onopen = function()
{
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var partsArray = evt.data.split('-');
lng=partsArray[0];
lat=partsArray[1];
alert(lat);
alert(lng);
};
ws.onclose = function() {
alert("Connection is closed...");
console.log("Connection is closed...");
};
}
else
{
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
<div>
<p id="para"> BASIC HTML!</p>
</div>
</body>
</html>
Thanks!
I'm assuming you're very new to all this web development. I haven't studied your code fully but the basic idea is you need a server side scripting language like JSP(of course JSP because you're using Java Code). I hope you know Javascript's basic idea is to use resources on the client's end, or to load data dynamically. So if you're only concerned with displaying some values from server to the client, you can simple make a servlet which will print your data.
Following MVC pattern,
Controller== Make a servlet which will handle the request made by user(i.e. the link which will show data,basically). Set your Model in this controller once you receive a request(you can decide what to do on GET/POST separately too).
Model== Make an abstract representation(class of Java) holding all your data that is to be displayed.
View== Here you'll receive the model. In other words, this will be your HTML. You can use JSP helpers to customize the view, the basic idea is to control HOW DATA WILL BE SHOWN TO THE USER(hence the name View). HTML will be automatically generated at run-time and passed to the user.
Again, I say I'm assuming you're very new to web development. Please let me know if I haven't understood your question well. Enjoy coding.

Categories