ORIGINAL EXCEPTION: ReferenceError: io is not defined - java

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?

Related

Flooding of message at side client from server channel and wrong message with CometD frame work

I am developing a client-server application, where I wanted to have a persistent connection between client-server, and I chose the CometD framework for the same.
I successfully created the CometD application.
Client -
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cometd.bayeux.Channel;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.LongPollingTransport;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import com.synacor.idm.auth.LdapAuthenticator;
import com.synacor.idm.resources.LdapResource;
public class CometDClient {
private volatile BayeuxClient client;
private final AuthListner authListner = new AuthListner();
private LdapResource ldapResource;
public static void main(String[] args) throws Exception {
org.eclipse.jetty.util.log.Log.getProperties().setProperty("org.eclipse.jetty.LEVEL", "ERROR");
org.eclipse.jetty.util.log.Log.getProperties().setProperty("org.eclipse.jetty.util.log.announce", "false");
org.eclipse.jetty.util.log.Log.getRootLogger().setDebugEnabled(false);
CometDClient client = new CometDClient();
client.run();
}
public void run() {
String url = "http://localhost:1010/cometd";
HttpClient httpClient = new HttpClient();
try {
httpClient.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client = new BayeuxClient(url, new LongPollingTransport(null, httpClient));
client.getChannel(Channel.META_HANDSHAKE).addListener(new InitializerListener());
client.getChannel(Channel.META_CONNECT).addListener(new ConnectionListener());
client.getChannel("/ldapAuth").addListener(new AuthListner());
client.handshake();
boolean success = client.waitFor(1000, BayeuxClient.State.CONNECTED);
if (!success) {
System.err.printf("Could not handshake with server at %s%n", url);
return;
}
}
private void initialize() {
client.batch(() -> {
ClientSessionChannel authChannel = client.getChannel("/ldapAuth");
authChannel.subscribe(authListner);
});
}
private class InitializerListener implements ClientSessionChannel.MessageListener {
#Override
public void onMessage(ClientSessionChannel channel, Message message) {
if (message.isSuccessful()) {
initialize();
}
}
}
private class ConnectionListener implements ClientSessionChannel.MessageListener {
private boolean wasConnected;
private boolean connected;
#Override
public void onMessage(ClientSessionChannel channel, Message message) {
if (client.isDisconnected()) {
connected = false;
connectionClosed();
return;
}
wasConnected = connected;
connected = message.isSuccessful();
if (!wasConnected && connected) {
connectionEstablished();
} else if (wasConnected && !connected) {
connectionBroken();
}
}
}
private void connectionEstablished() {
System.err.printf("system: Connection to Server Opened%n");
}
private void connectionClosed() {
System.err.printf("system: Connection to Server Closed%n");
}
private void connectionBroken() {
System.err.printf("system: Connection to Server Broken%n");
}
private class AuthListner implements ClientSessionChannel.MessageListener{
#Override
public void onMessage(ClientSessionChannel channel, Message message) {
Object data2 = message.getData();
System.err.println("Authentication String " + data2 );
if(data2 != null && data2.toString().indexOf("=")>0) {
String[] split = data2.toString().split(",");
String userString = split[0];
String passString = split[1];
String[] splitUser = userString.split("=");
String[] splitPass = passString.split("=");
LdapAuthenticator authenticator = new LdapAuthenticator(ldapResource);
if(authenticator.authenticateToLdap(splitUser[1], splitPass[1])) {
// client.getChannel("/ldapAuth").publish("200:success from client "+user);
// channel.publish("200:Success "+user);
Map<String, Object> data = new HashMap<>();
// Fill in the structure, for example:
data.put(splitUser[1], "Authenticated");
channel.publish(data, publishReply -> {
if (publishReply.isSuccessful()) {
System.out.print("message sent successfully on server");
}
});
}
}
}
}
}
Server - Service Class
import java.util.List;
import java.util.concurrent.BlockingQueue;
import org.cometd.bayeux.MarkedReference;
import org.cometd.bayeux.Promise;
import org.cometd.bayeux.server.BayeuxServer;
import org.cometd.bayeux.server.ConfigurableServerChannel;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.AbstractService;
import org.cometd.server.ServerMessageImpl;
import com.synacor.idm.resources.AuthenticationResource;
import com.synacor.idm.resources.AuthenticationResource.AuthC;
public class AuthenticationService extends AbstractService implements AuthenticationResource.Listener {
String authParam;
BayeuxServer bayeux;
BlockingQueue<String> sharedResponseQueue;
public AuthenticationService(BayeuxServer bayeux) {
super(bayeux, "ldapagentauth");
addService("/ldapAuth", "ldapAuthentication");
this.bayeux = bayeux;
}
public void ldapAuthentication(ServerSession session, ServerMessage message) {
System.err.println("********* inside auth service ***********");
Object data = message.getData();
System.err.println("****** got data back from client " +data.toString());
sharedResponseQueue.add(data.toString());
}
#Override
public void onUpdates(List<AuthC> updates) {
System.err.println("********* inside auth service listner ***********");
MarkedReference<ServerChannel> createChannelIfAbsent = bayeux.createChannelIfAbsent("/ldapAuth", new ConfigurableServerChannel.Initializer() {
public void configureChannel(ConfigurableServerChannel channel)
{
channel.setPersistent(true);
channel.setLazy(true);
}
});
ServerChannel reference = createChannelIfAbsent.getReference();
for (AuthC authC : updates) {
authParam = authC.getAuthStr();
this.sharedResponseQueue= authC.getsharedResponseQueue();
ServerChannel channel = bayeux.getChannel("/ldapAuth");
ServerMessageImpl serverMessageImpl = new ServerMessageImpl();
serverMessageImpl.setData(authParam);
reference.setBroadcastToPublisher(false);
reference.publish(getServerSession(), authParam, Promise.noop());
}
}
}
Event trigger class-
public class AuthenticationResource implements Runnable{
private final JerseyClientBuilder clientBuilder;
private final BlockingQueue<String> sharedQueue;
private final BlockingQueue<String> sharedResponseQueue;
private boolean isAuthCall = false;
private String userAuth;
private final List<Listener> listeners = new CopyOnWriteArrayList<Listener>();
Thread runner;
public AuthenticationResource(JerseyClientBuilder clientBuilder,BlockingQueue<String> sharedQueue,BlockingQueue<String> sharedResponseQueue) {
super();
this.clientBuilder = clientBuilder;
this.sharedQueue = sharedQueue;
this.sharedResponseQueue= sharedResponseQueue;
this.runner = new Thread(this);
this.runner.start();
}
public List<Listener> getListeners()
{
return listeners;
}
#Override
public void run() {
List<AuthC> updates = new ArrayList<AuthC>();
// boolean is = true;
while(true){
if(sharedQueue.size()<=0) {
continue;
}
try {
userAuth = sharedQueue.take();
// Notify the listeners
for (Listener listener : listeners)
{
updates.add(new AuthC(userAuth,sharedResponseQueue));
listener.onUpdates(updates);
}
updates.add(new AuthC(userAuth,sharedResponseQueue));
System.out.println("****** Auth consume ******** " + userAuth);
if(userAuth != null) {
isAuthCall = true;
}
} catch (Exception err) {
err.printStackTrace();
break;
}
// if (sharedQueue.size()>0) {
// is = false;
// }
}
}
public static class AuthC
{
private final String authStr;
private final BlockingQueue<String> sharedResponseQueue;
public AuthC(String authStr,BlockingQueue<String> sharedResponseQueue)
{
this.authStr = authStr;
this.sharedResponseQueue=sharedResponseQueue;
}
public String getAuthStr()
{
return authStr;
}
public BlockingQueue<String> getsharedResponseQueue()
{
return sharedResponseQueue;
}
}
public interface Listener extends EventListener
{
void onUpdates(List<AuthC> updates);
}
}
I have successfully established a connection between client and server.
Problems -
1- When I am sending a message from the server to the Client, the same message is sent out multiple times. I only expecting one request-response mechanism.
In my case- server is sending user credentila I am expecting result, whether the user is authenticated or not.
you can see in image how it is flooding with same string at client side -
2- There was other problem looping up of message between client and server, that I can be able to resolve by adding, but still some time looping of message is happening.
serverChannel.setBroadcastToPublisher(false);
3- If I change the auth string on sever, at client side it appears to be old one.
For example -
1 request from server - auth string -> user=foo,pass=bar -> at
client side - user=foo,pass=bar
2 request from server - auth string user=myuser,pass=mypass ->
at client side - user=foo,pass=bar
this are the three problems, please guide me and help me to resolve this.
CometD offer a request/response style of messaging using remote calls, both on the client and on the server (you want to use annotated services on the server).
Channel /ldapAuth has 2 subscribers: the remote client (which subscribes with authChannel.subscribe(...)), and the server-side AuthenticationService (which subscribes with addService("/ldapAuth", "ldapAuthentication")).
Therefore, every time you publish to that channel from AuthenticationService.onUpdates(...), you publish to the remote client, and then back to AuthenticationService, and that is why calling setBroadcastToPublisher(false) helps.
For authentication messages, it's probably best that you stick with remote calls, because they have a natural request/response semantic, rather than a broadcasting semantic.
Please read about how applications should interact with CometD.
About other looping, there are no loops triggered by CometD.
You have loops in your application (in AuthenticationService.onUpdates(...)) and you take from a queue that may have the same information multiple times (in AuthenticationResource.run() -- which by the way it's a spin loop that will likely spin a CPU core to 100% utilization -- you should fix that).
The fact that you see stale data it's likely not a CometD issue, since CometD does not store messages anywhere so it cannot make up user-specific data.
I recommend that you clean up your code using remote calls and annotated services.
Also, clean up your own code from spin loops.
If you still have the problem after the suggestions above, look harder for application mistakes, it's unlikely that this is a CometD issue.

grpc Client-Streaming Java Client gets io.grpc.StatusRuntimeException: UNAVAILABLE: HTTP status code 503

I have a grpc Nodejs server behind a HAproxy and client-streaming rpc java maven.
When I run the java client it return an error:
io.grpc.StatusRuntimeException: UNAVAILABLE: HTTP status code 503
invalid content-type: text/html headers:
Metadata(:status=503,cache-control=no-cache,content-type=text/html)
DATA-----------------------------
503 Service Unavailable No server is available to handle this request.
I already test a rpc client streaming with Nodejs and it worked.
My java client code:
public class App {
public static void main(String[] args) throws InterruptedException {
WebRTCStats stat = WebRTCStats.newBuilder().setUserId("abc").build();
SendWebRTCStats(stat);
}
public static void SendWebRTCStats(WebRTCStats stat) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forTarget("example.com:443").useTransportSecurity()
.build();
ClientGrpc.ClientStub stub = ClientGrpc.newStub(channel);
StreamObserver<Stat.Status> responseObserver = new StreamObserver<Stat.Status>() {
#Override
public void onNext(Stat.Status status) {
}
#Override
public void onError(Throwable t) {
t.printStackTrace();
}
#Override
public void onCompleted() {
System.out.print("complete");
}
};
StreamObserver<WebRTCStats> requestObserver = stub.sendWebRTCStats(responseObserver);
try {
// Send numPoints points randomly selected from the features list.
requestObserver.onNext(stat);
// Sleep for a bit before sending the next one.
} catch (RuntimeException e) {
// Cancel RPC
requestObserver.onError(e);
throw e;
}
// Mark the end of requests
requestObserver.onCompleted();
// Receiving happens asynchronously
}
}
My NodeJS server:
const PROTO_PATH = './stat.proto';
const grpc = require('grpc');
const protoLoader = require('#grpc/proto-loader');
const fs = require('fs');
const tcp = require('./using.js');
let packageDefinition = protoLoader.loadSync(PROTO_PATH);
let protoDescriptor = grpc.loadPackageDefinition(packageDefinition);
const server = new grpc.Server();
server.addService(protoDescriptor.Client.service, {
SendWebRTCStats: async (call, callback) => {
call.on('data', value => {
console.log(value);
tcp.sendLog("test", value);
});
call.on('end', () => {
callback(null, { status: 'success' });
})
},
});
let credentials = grpc.ServerCredentials.createSsl(
fs.readFileSync('ca.cer'), [{
cert_chain: fs.readFileSync('cer.crt'),
private_key: fs.readFileSync('cer_key.key')
}], false);
server.bind("0.0.0.0:443", credentials);
console.log("Server running at 443");
server.start();
Can this problem occurs by different implementations of different libraries of language in GRPC?
so apperently i changed forTarget("example.com) and it worked. I shouldnt specify port for it.

WARNING: RPC failed: Status{code=NOT_FOUND, description=Not found, cause=null} when trying to use GRPC in java and Nodejs

I am currently trying to send a request to a nodejs server from a java client that I created but I am getting the error that is showing above. I've been doing some research on it but can seem to figure out why it is happening. The server I created in nodejs:
var grpc = require('grpc');
const protoLoader = require('#grpc/proto-loader')
const packageDefinition = protoLoader.loadSync('AirConditioningDevice.proto')
var AirConditioningDeviceproto = grpc.loadPackageDefinition(packageDefinition);
var AirConditioningDevice = [{
device_id: 1,
name: 'Device1',
location: 'room1',
status: 'On',
new_tempature: 11
}];
var server = new grpc.Server();
server.addService(AirConditioningDeviceproto.AirConditioningDevice.Airconditioning_service.service,{
currentDetails: function(call, callback){
console.log(call.request.device_id);
for(var i =0; i <AirConditioningDevice.length; i++){
console.log(call.request.device_id);
if(AirConditioningDevice[i].device_id == call.request.device_id){
console.log(call.request.device_id);
return callback(null, AirConditioningDevice [i]);
}
console.log(call.request.device_id);
}
console.log(call.request.device_id);
callback({
code: grpc.status.NOT_FOUND,
details: 'Not found'
});
},
setTemp: function(call, callback){
for(var i =0; i <AirConditioningDevice.length; i++){
if(AirConditioningDevice[i].device_id == call.request.device_id){
AirConditioningDevice[i].new_tempature == call.request.new_tempature;
return callback(null, AirConditioningDevice[i]);
}
}
callback({
code: grpc.status.NOT_FOUND,
details: 'Not found'
});
},
setOff: function(call, callback){
for(var i =0; i <AirConditioningDevice.length; i++){
if(AirConditioningDevice[i].device_id == call.request.device_id && AirConditioningDevice[i].status == 'on'){
AirConditioningDevice[i].status == 'off';
return callback(null, AirConditioningDevice[i]);
}else{
AirConditioningDevice[i].status == 'on';
return callback(null, AirConditioningDevice[i]);
}
}
callback({
code: grpc.status.NOT_FOUND,
details: 'Not found'
});
}
});
server.bind('localhost:3000', grpc.ServerCredentials.createInsecure());
server.start();
This is the client that I have created in java:
package com.air.grpc;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.air.grpc.Airconditioning_serviceGrpc;
import com.air.grpc.GrpcClient;
import com.air.grpc.deviceIDRequest;
import com.air.grpc.ACResponse;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
public class GrpcClient {
private static final Logger logger = Logger.getLogger(GrpcClient.class.getName());
private final ManagedChannel channel;
private final Airconditioning_serviceGrpc.Airconditioning_serviceBlockingStub blockingStub;
private final Airconditioning_serviceGrpc.Airconditioning_serviceStub asyncStub;
public GrpcClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext()
.build());
}
GrpcClient(ManagedChannel channel) {
this.channel = channel;
blockingStub = Airconditioning_serviceGrpc.newBlockingStub(channel);
asyncStub = Airconditioning_serviceGrpc.newStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void currentDetails(int id) {
logger.info("Will try to get device " + id + " ...");
deviceIDRequest deviceid = deviceIDRequest.newBuilder().setDeviceId(id).build();
ACResponse response;
try {
response =blockingStub.currentDetails(deviceid);
}catch(StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Device: " + response.getAirConditioning ());
}
public static void main(String[] args) throws Exception {
GrpcClient client = new GrpcClient("localhost", 3000);
try {
client.currentDetails(1);
}finally {
client.shutdown();
}
}
}
Right now the only one that I have tested cause its the most basic one is currentdetails. As you can see I have created an AirConditioningDevice object. I am trying to get the details of it by typing in 1 to a textbox which is the id but like i said when i send it i get the error in the title. This is the proto file that I have created:
syntax = "proto3";
package AirConditioningDevice;
option java_package = "AircondioningDevice.proto.ac";
service Airconditioning_service{
rpc currentDetails(deviceIDRequest) returns (ACResponse) {};
rpc setTemp( TempRequest ) returns (ACResponse) {};
rpc setOff(deviceIDRequest) returns (ACResponse) {};
}
message AirConditioning{
int32 device_id =1;
string name = 2;
string location = 3;
string status = 4;
int32 new_tempature = 5;
}
message deviceIDRequest{
int32 device_id =1;
}
message TempRequest {
int32 device_id = 1;
int32 new_temp = 2;
}
message ACResponse {
AirConditioning airConditioning = 1;
}
lastly this is everything I get back in the console:
Apr 02, 2020 4:23:29 PM AircondioningDevice.proto.ac.AirConClient currentDetails
INFO: Will try to get device 1 ...
Apr 02, 2020 4:23:30 PM AircondioningDevice.proto.ac.AirConClient currentDetails
WARNING: RPC failed: Status{code=NOT_FOUND, description=Not found, cause=null}
I dont know whether I am completely off or if the error is small. Any suggestions? One other thing is I the same proto file in the java client and the node server I dont know if that matters. One last this is I also get this when i run my server: DeprecationWarning: grpc.load: Use the #grpc/proto-loader module with grpc.loadPackageDefinition instead I dont know if that has anything to do with it.
In your .proto file, you declare deviceIDRequest with a field device_id, but you are checking call.request.id in the currentDetails handler. If you look at call.request.id directly, it's probably undefined.
You also aren't getting to this bit yet, but the success callback is using the books array instead of the AirConditioningDevice array.

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