It's been days that I struggle to make a basic Client / server communication using websockets
My client is a java client with libGDX and my server is a basic java server
My main goal is to compile my client into HTML5 to communicate with my server using websockets.
I tryed the following solution when searching on google :
https://github.com/czyzby/gdx-lml/tree/master/websocket
https://github.com/pepedeab/libGDX-Net
https://github.com/TooTallNate/Java-WebSocket
The 1 seemed to be the best solution but, it doesn't seems to have the TCP_NODELAY socket setting (which is essential in my case)
The 2 seemed an other good solution too, But it relies on http://code.google.com/p/gwt-ws/(which at this time don't understand the point of this)
The 3 is what I choosed, a simple WebSocket Java API to let me write client and server really easily.
It worked very well for desktop and android, but when I tryed to html:dist, gradle give me error about websocket which was not inherit etc...
My main build.gradle file contains this line for each project (core, desktop, android, html) : compile "org.java-websocket:Java-WebSocket:1.3.7"
So to resume my primary question : How to correctly establish a websocket connection with a client compiled with GWT in ligdx, with in addition TCP_NODELAY?
My client is a very simple class :
package com.mygdx.game;
import java.net.URI;
import java.nio.ByteBuffer;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
public class WebSocketsNet extends WebSocketClient {
public WebSocketsNet(URI serverUri, Draft draft) {
super(serverUri, draft);
}
public WebSocketsNet(URI serverURI) {
super(serverURI);
}
#Override
public void onOpen(ServerHandshake handshakedata) {
send("Hello, it is me. Mario :)");
System.out.println("new connection opened");
}
#Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("closed with exit code " + code + " additional info: " + reason);
}
#Override
public void onMessage(String message) {
System.out.println("received message: " + message);
}
#Override
public void onMessage(ByteBuffer message) {
System.out.println("received ByteBuffer");
}
#Override
public void onError(Exception ex) {
System.err.println("an error occurred:" + ex);
}}
According to https://bugs.webkit.org/show_bug.cgi?id=102079 and https://groups.google.com/forum/#!topic/native-client-discuss/T8zdrMjiTAE, found via https://github.com/websockets/ws/issues/791 and https://github.com/varspool/Wrench/pull/104, most browsers already use TCP_NODELAY. At least from the websocket standard, there is nothing you can do to influence this on the client - on the server there may be more options.
If TCP_NODELAY is already set on the client, you can set it on the server as well to ensure both sides are sending small messages as soon as possible.
Another thought that is suggested in questions like https://stackoverflow.com/a/13406438/860630 is to respond to every message sent right away, so that the network stack flushes all remaining messages as soon as possible.
Finaly I found a way to make it work, so I post a answer here for those interested.
I used https://github.com/czyzby/gdx-lml/tree/master/websocket
Particulary the example package, and rigorously follow everything that need to be added on build.gradle and on differents xml files, so now it work !
So to conclude :
Server Listening websockets with java-web-socket
LIBGDX client use gdx-websockets to connect to the server (Watch-out for different build gradle file and xml !!)
Hope to help some people who were in the same problem like me !
Related
I've been working on a service with java tutorial, and was listening to it through localhost:8082. It was working just fine, but since I've turned off the computer it returns the error connection refused when I try to listen to it, and the only ports that present different responses are 8080 and 8081, which get the same error when I try to listen to the service through them.
Here's the code:
package io.vertx.book.message;
import io.vertx.core.json.JsonObject;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.eventbus.Message;
import rx.Single;
public class HelloConsumerMicroservice extends AbstractVerticle {
#Override
public void start() {
vertx.createHttpServer()
.requestHandler(
req -> {
Single<JsonObject> obs1 = vertx.eventBus()
.<JsonObject>rxSend("hello", "Luke")
.map(Message::body);
Single<JsonObject> obs2 = vertx.eventBus()
.<JsonObject>rxSend("hello", "Leia")
.map(Message::body);
Single
.zip(obs1, obs2, (luke, leia) ->
new JsonObject()
.put("Luke", luke.getString("message")
+ " from " + luke.getString("served-by"))
.put("Leia", leia.getString("message")
+ " from " + leia.getString("served-by"))
)
.subscribe(
x -> req.response().end(x.encodePrettily()),
t -> req.response().setStatusCode(500).end(t.getMessage())
);
})
.listen(8082);
}
}
That's the response I've got:
I don't know why it stopped working, but I've already browsed through a lot of answers and already tried cleaning my cache, but no improvements. Could anyone help?
I'm using Linux 18.04, Chrome/Firefox (both get connection refused).
As your using Ubuntu it might be your firewall not allowing connections to that port.
Open a terminal and type
sudo ufw allow 8082
Hopefully that helps
Somehow after shytting everything down and restarting the machine, everything came back to normal, so... Don't know what happened, but it's all right now... It might've been used by something else. Thanks anyways for the help!
I am currently writing a small Java applet to access HBase data using the REST API. Accessing the data using Java is not particularly difficult, I have done this successfully. When running on a machine in my HDP cluster, the results are perfect. However when running as an applet I get no results at all. (I have chosen an applet since distributing an executable JAR is something my boss wants to avoid)
Having finally found what I believe to be the underlying issue, I have found the following runtime exception: hbase-default.xml file seems to be for an older version of HBase (null), this version is 1.1.2.2.4.0.0-169. My assumption is that this is caused by the fact that my local machine does not have HBase at all. The intention is that users will be able to view their own data from a local machine, and so I cannot expect all users to have HBase (or anything other than a browser)
My question really has two parts:
Is there anyway to get an applet like this to work?
Is there a better alternative to an applet for this kind of work?
Posting my code in case I have made some significant mistake:
public class HBaseConnector extends JApplet
{
private Cluster cluster;
public void init()
{
System.out.println("Applet initialising");
cluster = new Cluster();
cluster.add("hbase_server", 9080);
}
public void start()
{
System.out.println("Applet starting");
Client client = new Client(cluster);
RemoteHTable table = new RemoteHTable(client, "table_name");
Get get = new Get(Bytes.toBytes("key"));
get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("Record"));
try
{
Result result1 = table.get(get);
JOptionPane.showMessageDialog(null, Bytes.toString(result1.getValue(Bytes.toBytes("f1"), Bytes.toBytes("Record"))), "Result", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
System.err.println("Exception occurred");
}
}
public void stop()
{
System.out.println("Applet stopping");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
While I haven't been able to solve this problem for an applet itself, I managed to get the app working by moving over the a JNLP app (JNLP). Given this, I suspect the underlying problem was a permissions issue due to the fact that applets run in a sandbox. This is fine, since I am aware that most browsers are moving away from Java plugins.
Another possible cause I discovered: hbase-default.xml must be in the root folder of the jar.
My smartphone collects GPS, Bluetooth log, then periodically send the data to server.
My server continuously receive the data by using Restlet.
However i encounter a error which i have never seen before and Google does not give any solution or hints. (my server has worked well for the past few days.)
Following message is errors i encountered.
Unable to run the following server-side task: sun-net.httpserver.ServerImpl$Exchange#81a5dc
Unable to run the following server-side task: sun-net.httpserver.ServerImpl$Exchange#~~~~~~
Unable to run the following server-side task: sun-net.httpserver.ServerImpl$Exchange#~~~~~~
Following is my code.
RestletServerMain.java
public void restServer(){
try{
Component component = new Component();
component.getServers().add(Protocol.HTTP, Integer.parseInt(Common.SERVER_PORT));
component.getDefaultHost().attach(new ServerApplication());
component.start();
}catch(Exception e){
e.printStackTrace();
}
}
ServerApplication.java
public class ServerApplication extends Application {
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attach("/dataprocessing1", xxx.class);
router.attach("/dataprocessing2", yyy.class);
return router;
}
It could be interesting to try the jetty extension (org.restlet.extends.jetty) of Restlet (instead of the default one).
Just add the corresponding jar file in your classpath and Jetty will be used as underlying server for your application.
Hope it will fix your issue.
Thierry
I'm currently learning Java by developing a tool for creating and filling out multiple-choice-forms client-side and saving aswell as evaluating them server-side. I used a code skeleton from a RMI Tutorial for the network-part and it was working fine until just now. Both the client and the server application are in the same package but run as seperate applications. For easier developing they're both running on the same system right now, although this will change when things are done.
So let's cut to the chase with some code and what exactly goes wrong:
Server.java
Server() throws RemoteException {
super();
}
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
}
catch (RemoteException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
try {
Naming.rebind("Server", new Server()); <---
}
catch(MalformedURLException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
catch(RemoteException ex) {
System.out.println("SERVER: " + ex.getMessage());
}
}
[...] methods that are called by the client via ServerInterface
The <--- marks where the Client-GUI is started.
Client.java
private static Gui_loadSets gui_loadSets = new Gui_loadSets();
public static void main(String[] args) {
loadGuiLoadSets();
}
This is where the first GUI is turned visible; the one to choose a form to load from. This GUI is loaded by starting the server EVEN IF I COMMENT THIS OUT. So the Server doesn't really load the Client-App, but instead somehow magically accesses it's GUI and showing it for no reason.
I already tried "stepping into" the line before the GUI is loaded, but I end up in an infinite loop eventually, so I really have no idea what is going an.
This is my first question here, so please forgive me if I missed out anything obvious.
Thanks for your help in advance. If you need any more code I'd be happy to supply, but most of the remaining code is all about the multiple-choice-forms.
Naming.rebind() needs a URL, not just a service name. It should be
Naming.rebind("rmi://localhost/Server", new Server());
But I'm puzzled by your comment on this line. The --> doesn't 'mark where the Client-GUI is started', it marks the line where the remote object is constructed, exported, and bound into the Registry. The client GUI is at the client.
Thanks for your effort, I got it working now.
A very basic class the server was creating an object from was referring to a method provided by the client. So apparently this caused the problem. I must've forgotten about it, since it was in there since the beginning but somehow just now started to turn out to be a visible problem.
I'm sorry for any inconvenience my bad design has caused you. :)
Also, how do I mark this problem as solved without being frowned upon? Do people attach importance to getting the accepted-answer-button? I can't do this on comments I believe.
I am trying to get started with WebSockets, and trying to write a simple application to send messages back and forth via a websoket.
However, it looks like the socket that I am trying to create never gets connected. Why can that be?
Below is the code of my WebSockets class. When .onConnect() is called, it logs:
I am socket, I was connected. Am i connected? - false
Update: in JavaScript, where I create the socket in question, the readyState is 1, which means "socket open, communication is possble".
import a.b.Misc; //writes logs.
import com.sun.grizzly.websockets.BaseServerWebSocket;
import com.sun.grizzly.websockets.DataFrame;
import com.sun.grizzly.websockets.WebSocketListener;
public class ChatWebSocket_v2 extends BaseServerWebSocket {
private String user;
public ChatWebSocket_v2(WebSocketListener... listeners) {
super(listeners);
}
public String getUser() {
if (user == null) {
Misc.print("User is null in ChatWebSocket");
throw new NullPointerException("+=The user is null in chat web socket");
}
return user;
}
public void setUser(String user) {
Misc.print("Just set user: " + user);
this.user = user;
}
#Override
public void onMessage(String message) {
Misc.print(message +"\n");
}
#Override
public void onMessage(byte[] message) {
Misc.print(new String(message) +" << Bytes\n");
}
#Override
public void onConnect() {
Misc.print("I am socket, i was connected. Am i connected? - " + this.isConnected());
}
#Override
public void onClose(DataFrame df) {
Misc.print("I am socket, i was closed");
}
}
If you're just trying to make a connection somewhere, you might want to try this instead. There is a live working demo and you can download the javascript code and play with it yourself. Note that the javascript code only works if you have it installed on a server (due to browser security because it's 'fancy'.) There is also a step by step browser-based client tutorial in the works that I will post as soon as it's ready. Most proxy servers haven't been upgraded to handle websockets so they will screw up connection request and most people won't be able to connect to websocket servers from work. Firefox 7 (release) or Google Chrome 14 or later support the latest version of the websocket protocol that the demo server runs.
If you want to try to get the grizzly demo working, you might have some debugging to do and maybe I'll help with that. Note that in comments below the article, other people said they couldn't get it working either and I haven't found any follow up. At this point it seems no better than the echo app above even if we do get it running and is possibly overly complicated and underly documented if you're just trying to get started. But if you want to try to get it running, you should 'git' the latest version of the code here, which was at least committed recently and may be fixed.
Then make sure that app.url in the application javascript file is set to your installation directory. His is hard-coded as:
url: 'ws://localhost:8080/grizzly-websockets-chat/chat',
If you're using Firefox 7, the javascript needs to be modified to use the Moz prefix, for example:
if (typeof MozWebSocket != "undefined") { // window.MozWebSocket or "MozWebSocket" in window
ok
} else if (window.WebSocket) { // he uses if ("WebSocket" in window)
ok
} else {
do your print "browser doesn't support websockets"
}
.... then if the browser supports websockets
websocket = new WebSocket(app.url); or
websocket = new MozWebSocket(app.url);
// depending on which it is.
The HLL websocket server demo code has this all sorted out.
(another) UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.