SparkJava websocket not working - java

SparkJava web sockets won't work. Whenever I attempt to connect to it with a websocket tester, at 'ws://localhost:4567/echo' it gets an error 'undefined' and never connects, nor do any of the sout's or printStackTrace get called.
#WebSocket
public class EchoWebSocket {
private static final Queue<Session> sessions = new ConcurrentLinkedQueue<>();
#OnWebSocketConnect
public void connected(Session session) {
System.out.println("Client connected");
//sessions.add(session);
}
#OnWebSocketClose
public void closed(Session session, int statusCode, String reason) {
System.out.println("Client disconnected");
//sessions.remove(session);
}
#OnWebSocketMessage
public void message(Session session, String message) throws IOException {
System.out.println("Got: ");// + message); // Print message
//session.getRemote().sendString(message); // and send it back
}
#OnWebSocketError
public void throwError(Throwable error) {
error.printStackTrace();
}
}
how I call it
Spark.webSocket("/echo", new EchoWebSocket());
Spark.init();

You need to define the class, not create an object.
Spark.webSocket("/echo", EchoWebSocket.class);

Related

SignalR java client can't invoke method and send data

I created a basic selfhosted SignalR server with the following code:
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
Which is taken from: https://learn.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host and works with the Javascript client.
I am now trying to create a Java client and got the following code that is simply supposed to send a message to the server:
String host = "http://localhost:8080";
HubConnection connection = new HubConnection(host);
HubProxy proxy = connection.createHubProxy("MyHub");
connection.start();
try {
System.out.println("Sendng message...");
proxy.invoke( "Send", "Client", "Hello world!" ).get();
System.out.println("Message sent!");
} catch (InterruptedException e) {
System.out.println("err1");
// Handle ...
} catch (ExecutionException e) {
System.out.println("err2");
// Handle ...
}
The problem that im having is that the message is not received by the server, it seems like the code is stuck at the invoke call and doesn't print the Hello world! message. Does someone know what im doing wrong?
hubProxy.invoke("sendMessageByUser", Message, WebApiToken).done(new Action<Void>() {
#Override
public void run(Void aVoid) {
if (aVoid != null)
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyApplicationService.this, "Mesaj gönderildi", Toast.LENGTH_SHORT).show();
}
});
}
}).onError(new ErrorCallback() {
#Override
public void onError(final Throwable error) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyApplicationService.this.getApplicationContext(), "Bir hata oluştu" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});

websocket string onMessage, gives java.lang.IllegalStateException: Binary message handler not found

I have a websocket setup using javax.websocket, it seems to connect, but wont work, it keeps giving a java.lang.IllegalStateException: Binary message handler not found
final WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
Session session = webSocketContainer.connectToServer(new Endpoint() {
#Override
public void onError(Session session, Throwable thr) {
// TODO Auto-generated method stub
super.onError(session, thr);
System.out.println("checkerWindow.DownloadMessages().new Endpoint() {...}.onError()");
thr.printStackTrace();
}
#Override
public void onOpen(Session session, EndpointConfig EndpointConfig) {
System.out.println("checkerWindow.DownloadMessages().new Endpoint() {...}.onOpen()");
try {
//send login details
//login:<deviceid>:<secret>\n
session.getBasicRemote().sendText("login:"+deviceid+":"+secret+"\n");
}
catch(Exception ex){
System.err.println("Exception=" + ex.toString());
ex.printStackTrace();
}
}
#OnMessage
public void onMessage(String message) {
System.out.println("Received message: "+message);
}
#Override
public void onClose(Session session, CloseReason closeReason) {
System.out.println("checkerWindow.DownloadMessages().new Endpoint() {...}.onClose()");
}
}, ClientEndpointConfig.Builder.create().build(), URI.create("wss://client.pushover.net/push"));
I have tried the ByteBuffer but the compiler doesnt like that.
You should define a method to receive binary messages. For example,
#OnMessage
public void onMessage(byte[] message) {
......
}
See the JavaDoc of OnMessage annotation for details.

Java Eclipse Paho Implementation - Auto reconnect

I'm trying to implement eclipse.paho in my project to connect Mqtt Broker (Both subscribing and publishing purpose). The problem is, when I using the subscribing feature (Implementing MqttCallback interface), I couldn't figure our how can I reconnect if the connection lost. MqttCallback interface has a connectionLost method, but it is useful for the debug what causes the connection lost. I searched but couldn't find a way to establish auto reconnect. Can you suggest a way or document about this problem?
I'm using the paho client 1.2.0.
With the MqttClient.setAutomaticReconnect(true) and interface MqttCallbackExtended API, and thanks to https://github.com/eclipse/paho.mqtt.java/issues/493, I could manage to reconnect automatically when the connection to broker is down.
See below the code.
//Use the MqttCallbackExtended to (re-)subscribe when method connectComplete is invoked
public class MyMqttClient implements MqttCallbackExtended {
private static final Logger logger = LoggerFactory.getLogger(MqttClientTerni.class);
private final int qos = 0;
private String topic = "mytopic";
private MqttClient client;
public MyMqttClient() throws MqttException {
String host = "tcp://localhost:1883";
String clientId = "MQTT-Client";
MqttConnectOptions conOpt = new MqttConnectOptions();
conOpt.setCleanSession(true);
//Pay attention here to automatic reconnect
conOpt.setAutomaticReconnect(true);
this.client = new org.eclipse.paho.client.mqttv3.MqttClient(host, clientId);
this.client.setCallback(this);
this.client.connect(conOpt);
}
/**
* #see MqttCallback#connectionLost(Throwable)
*/
public void connectionLost(Throwable cause) {
logger.error("Connection lost because: " + cause);
/**
* #see MqttCallback#deliveryComplete(IMqttDeliveryToken)
*/
public void deliveryComplete(IMqttDeliveryToken token) {
}
/**
* #see MqttCallback#messageArrived(String, MqttMessage)
*/
public void messageArrived(String topic, MqttMessage message) throws MqttException {
logger.info(String.format("[%s] %s", topic, new String(message.getPayload())));
}
public static void main(String[] args) throws MqttException, URISyntaxException {
MyMqttClient s = new MyMqttClient();
}
#Override
public void connectComplete(boolean arg0, String arg1) {
try {
//Very important to resubcribe to the topic after the connection was (re-)estabslished.
//Otherwise you are reconnected but you don't get any message
this.client.subscribe(this.topic, qos);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
The best way to do this is to structure your connection logic so it lives in a method on it's own so it can be called again from the connectionLost callback in the MqttCallback instance.
The connectionLost method is passed a Throwable that will be the exception that triggered the disconnect so you can make decisions about the root cause and how this may effect when/how you reconnect.
The connection method should connect and subscribe to the topics you require.
Something like this:
public class PubSub {
MqttClient client;
String topics[] = ["foo/#", "bar"];
MqttCallback callback = new MqttCallback() {
public void connectionLost(Throwable t) {
this.connect();
}
public void messageArrived(String topic, MqttMessage message) throws Exception {
System.out.println("topic - " + topic + ": " + new String(message.getPayload()));
}
public void deliveryComplete(IMqttDeliveryToken token) {
}
};
public static void main(String args[]) {
PubSub foo = new PubSub();
}
public PubSub(){
this.connect();
}
public void connect(){
client = new MqttClient("mqtt://localhost", "pubsub-1");
client.setCallback(callback);
client.connect();
client.subscribe(topics);
}
}
To use auto reconnect, just set setAutomaticReconnect(true) on the MqttConnectOptions object.
MqttAndroidClient mqttClient = new MqttAndroidClient(context, mqttUrl, clientId);
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttClient.connect(mqttConnectOptions, null, mqttActionListener());

How I create a simple Socket.io server for connecting with socket.io-java-client on android app?

I have a client-side java code running in my Android Activity using the Gottox/socket.io.-java-client implementation on Github. This is the client code that needs to simple connect to a server and receive messages from it from time to time. Please bear with me as I'm very new to this domain and might be understanding this completely wrong!
This is what my client code looks like right now:
package com.example.culami;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import org.json.JSONException;
import org.json.JSONObject;
public class AcknowledgeExample implements IOCallback {
private SocketIO socket;
int connectionEstablished;
/**
* #param args
*/
/*public static void main(String[] args) {
try {
new AcknowledgeExample();
} catch (Exception e) {
e.printStackTrace();
}
}*/
public AcknowledgeExample() throws Exception
{
connectionEstablished = 0;
socket = new SocketIO();
socket.connect("http://192.168.0.108:3000/", this);
//socket.connect("http://localhost:3000/", this);
// Sends a string to the server.
//socket.send("Hello Server");
// Sends a JSON object to the server.
//socket.send(new JSONObject().put("key", "value").put("key2", "another value"));
//socket.send("server says hello!");
// Emits an event to the server.
//socket.emit("event", "argument1", "argument2", 13.37);
}
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
#Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
#Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
#Override
public void onConnect() {
System.out.println("Connection established");
connectionEstablished = 1;
}
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
}
The server side code I'm currently trying to work with is taken from Socket.io's getting started tutorial page and looks as under:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res)
{
//res.sendFile(__dirname + '/index.html');
res.send('<h1>Hello world</h1>');
});
io.on('connection', function(socket)
{
console.log('a user connected');
/*socket.on('chat message', function(msg)
{
io.emit('chat message', msg);
});*/
});
All I need is to figure out a way to make my client and server codes connect. The server side code needs to be java script as sends the client a string keyword/message from time to time. Any pointers/suggestions/fixes will be highly appreciated.

Java EE Websocket: How to send keep sending data without receiving message?

What I want?
I am trying to write an application where client sends a query and based on the query server gets twitter-stream and pushes to client.
What I have?
I have a simple structure in place where client can connect to server and server responds back
TweetStreamServer
package com.self.tweetstream;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/tweets")
public class TweetStreamServer {
#OnMessage
public String tweets(final String message) {
return message;
}
}
TweetStreamClient
#ClientEndpoint
public class TweetStreamClient {
public static CountDownLatch latch;
public static String response;
#OnOpen
public void onOpen(Session session) {
try{
session.getBasicRemote().sendText("Hello World!");
} catch (IOException e) {
e.printStackTrace();
}
}
#OnMessage
public void printTweets(final String tweet) {
System.out.println("Tweet:" + tweet);
response = tweet;
latch.countDown();
}
}
TweetStreamTest
#Test
public void test() throws URISyntaxException, IOException, DeploymentException, InterruptedException {
System.out.println("URI: " + getEndpointUrl());
TweetStreamClient.latch = new CountDownLatch(1);
Session session = connectToServer(TweetStreamClient.class, "tweets");
assertNotNull(session);
assertTrue(TweetStreamClient.latch.await(10, TimeUnit.SECONDS));
assertEquals("Hello World!", TweetStreamClient.response);
}
Question
I am confused how can I now send continuous tweets that I receive from Twitter because my server method as per API is
#OnMessage
public String tweets(final String message) {
return message;
}
This means it expects a message in order return anything.
How can I send on-coming data from Twitter send to client?
This worked for me
#OnMessage
public void tweets(final String message, Session client) throws IOException, InterruptedException {
int i = 0;
for (Session peer : client.getOpenSessions()) {
while (i < 10) {
System.out.println("sending ...");
peer.getBasicRemote().sendText("Hello");
Thread.sleep(2000);
i++;
}
}
}
Thanks to Arun Gupta for helping through his tweets :)

Categories