Giter VIP home page Giter VIP logo

socket.io-server-java's Introduction

Socket.IO Java

Build Status codecov

This is the Socket.IO Server Library for Java ported from the JavaScript server.

NOTE This library will follow the major version of the JS library starting with version 3.

See also: Socket.IO-client Java

Features

This library supports all of the features the JS server does, including events, options and upgrading transport.

Documentation

Complete documentation can be found here.

Installation

The latest artifact is available on Maven Central.

Maven

Add the following dependency to your pom.xml.

<dependencies>
  <dependency>
    <groupId>io.socket</groupId>
    <artifactId>socket.io-server</artifactId>
    <version>4.0.1</version>
  </dependency>
</dependencies>

Gradle

Add it as a gradle dependency in build.gradle.

compile ('io.socket:socket.io-server:4.0.1')

Demo project

A basic demo project running on a Jetty server can be found at https://github.com/oddmario/socket.io-server-java-demo

License

Apache 2.0

socket.io-server-java's People

Contributors

dependabot[bot] avatar oddmario avatar trinopoty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socket.io-server-java's Issues

No able to see in the network tab

Hi @trinopoty
We are broad casting a message but internally we are seeing that backslashes, escape characters, \n are being added is there a way to prevent it as we are seeing this error in network tab

Getting client's ip address (Socket io v2)

I am using 1.0.3 version of this library (with engine.io server 1.3.5) that supports Socket.io v2. I am looking to get the ip address of the connected client. V2 Server API documentation https://socket.io/docs/v2/server-api/#sockethandshake, suggests that socket.handshake.address should provide the ip of the client. But I can't see that in this library. Any pointers for this? Thanks!

{
  headers: /* the headers sent as part of the handshake */,
  time: /* the date of creation (as string) */,
  address: /* the ip of the client */,
  xdomain: /* whether the connection is cross-domain */,
  secure: /* whether the connection is secure */,
  issued: /* the date of creation (as unix timestamp) */,
  url: /* the request URL string */,
  query: /* the query object */
}

Middleware Support

Thanks for the port. I don't think this supports adding middlewares. Is that correct or I missed it somewhere? (Duplicates socketio#1)

I am looking for creating a forwarding server that listens to all event. Looking at nodejs server implementations, looks like middlewares can allow that. Any thoughts or suggestions, please? TIA!

tests do not test SocketIoServer

Hey there, I'm taking a look at socket.io-server-java and in the tests (ServerWrapper) I noticed you've declared mSocketIoServer but it's never actually used in the code. The test seem to run on Engine.IO with a custom JettyWebSocketHandler included from another mysterious java module. Am I missing something?

Jetty v11 support

Hi

Thanks for great implementation.

Do you have any plan for Jetty 11 upgrade?

Since Jetty 11 has "big bang" change, there is no javax.servlet.* it is now jakarta.servlet.*.

So I upgraded in my fork with following jakarta dependency(And many other import changes) I successfully compile Engine.io-server-java and socket.io-server-java.

But unfortunately, I couldn't pass the socket.io-server-tests since Initialization of websocket has changed dramatically.

https://www.eclipse.org/jetty/documentation/jetty-11/programming-guide/index.html#pg-server-http-handler-use-webapp-context
// Setup the ServerContainer and the WebSocket endpoints for this web application context.
JakartaWebSocketServletContainerInitializer.configure(handler, (servletContext, container) ->
{
// Configure the ServerContainer.
container.setDefaultMaxTextMessageBufferSize(128 * 1024);

        // Simple registration of your WebSocket endpoints.
        //container.addEndpoint(PoCJettyWebsocketHandler.class);

        // JettyWebSocketHandler  Constructor requires args but even if I create empty constructor it does not call methods
        ServerEndpointConfig config = ServerEndpointConfig.Builder.create(JettyWebSocketHandler.class, "/socket.io/")
                .build();
        container.addEndpoint(config);
    });

Would you help me to run if I create PR?

    <dependency>
        <groupId>jakarta.platform</groupId>
        <artifactId>jakarta.jakartaee-api</artifactId>
        <version>9.1.0</version>
        <scope>provided</scope>
    </dependency>

Redis adapter and how to implement adapter

Hi. Does it have any redis adapter implementation ?
I have tried implement adapter, but the library have much restriction about private method/class.
How can I do that

Acknowledgement callback without namespace

Server side with Kotlin:

	namespace = socketIoServer.namespace("/chat")
	namespace.on("connection") { clients ->
		val client = clients.firstOrNull() as? SocketIoSocket
		client?.on("custom-event") {
			val callback = it.firstOrNull() as? SocketIoSocket.ReceivedByLocalAcknowledgementCallback
			callback?.sendAcknowledgement("hello callback")
		}
	}

Client side with TypeScript:

	const socket = io("http://myspace:8080/chat", {
		transports: ["websocket"],
	})
	socket.on("connect", () => {
		socket.emit("custom-event", function(data?: any) {
			console.log(data) 
		})
	})

Client side emit message:

42/chat,0["custom-event"]

PROBLEM:

The Acknowledgement callback event sent by server without namespace:

430["hello callback"]

Backward compatibility of v4

This comment refers to v4 being compatible with all previous versions.

With that comment, I am testing upgrade of server library from 1.0.3 to 4.0.1. I use postman socket.io client for testing. Socket IO v2 requests that works with 1.0.3, are not working with 4.0.1. The connection request just hangs up and events are not received on server.

Is v4 backward compatible for previous socket.io versions?

image

QUESTION: JAVA Server .... but non JAVA client? Viz?

Hi,
I have successfully implemented SocketIO on JS and Dart/flutter. Both as client & server.

I wanted to know(with Regards to SocketIO) before I get into the building of an entire project... Can a JAVA client... interact with my JS server(NodeJS)...?
or even JAVA Server interact with JS client... or may be a Dart/flutter client... or anything else?

I ask this cause I managed a Dart Client with NodeJS server flawlessly.... But since it was a flutter Web project... I was not sure.

Thanks!

Infinite service requests resulting in TcpSocketLink OutOfMemory

I'm testing out your socket.io solution...

I've got 1 Test user, using chrome browser (latest version) + socket.io (latest JS version)
Our Resin4 server: Using your "socket.io-client" solution, this server sends out notifications to our test user via the socket server

wsclient.js - connection setup

$(function () {

// make connection

let socket = io.connect();

console.log("Websocket connected");

...

I've tested this setup with node.js+socket-io server.js (a more complete script than the code below) and it works perfectly.

Now, as a test, I decided to disable node.js and try your socket.io-server solution by following your documentation (as best I could), I've modified it slightly, but I get the same quirks whether I follow your instructions explicitly or not.
I start my Resin4 server (same server mentioned above, but including the following servlet)
It runs ok for a few seconds handling the socket.io-client(java) connection ok, but then it then has major issues (described further below).
Note:
I also tried
let socket = io.connect('ws://localhost:8080/socket.io/?user=test');
with same results

package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.socket.emitter.Emitter;
import io.socket.engineio.server.EngineIoServer;
import io.socket.socketio.server.SocketIoNamespace;
import io.socket.socketio.server.SocketIoServer;
import io.socket.socketio.server.SocketIoSocket;

@WebServlet("/socket.io/*")
public class SocketIoServlet extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private final EngineIoServer mEngineIoServer = new EngineIoServer();

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("[WEBSOCKET] SOCKET.IO: doGet");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	System.out.println("[WEBSOCKET] SOCKET.IO: doPost");
}

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	mEngineIoServer.handleRequest(request, response);
	
	SocketIoServer mSocketIoServer = new SocketIoServer(mEngineIoServer);  // << this seems to result in less repeated iterations
	SocketIoNamespace namespace = mSocketIoServer.namespace("/");
	
	namespace.on("connection", new Emitter.Listener() {
		@Override
		public void call(Object... args) {
			SocketIoSocket socket = (SocketIoSocket) args[0];
			System.out.println("[SOCKET.IO] Connection. Args=" + args.length+" Socket id=" + socket.getId());

			socket.on("message", new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					try {
						System.out.println("[SOCKET.IO] Message. Args=" + args.length);
						System.out.println(args[0]);
					} catch (Exception e) {
						System.out.println("Error");
					}
				}
			});
			socket.on("notify", new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					try {
						System.out.println("[SOCKET.IO] Message. Args=" + args.length);
						System.out.println(args[0]);
					} catch (Exception e) {
						System.out.println("Error");
					}
				}
			});
			socket.on("ping", new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					System.out.println("[SOCKET.IO] Ping");
				}
			});
			socket.on("pong", new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					System.out.println("[SOCKET.IO] Pong");
				}
			});
			socket.on("error", new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					System.out.println("[SOCKET.IO] Error");
				}
			});

		}
	});
}

public void init() throws ServletException {
	System.out.println("[WEBSOCKET] SOCKET.IO: Init");
	
}

public void destroy() {
	System.out.println("[WEBSOCKET] SOCKET.IO: DESTROYED");
}

}

The log file reports...

[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ
[SOCKET.IO] Connection. Args=1 Socket id=N9k8mvJ

(repeats forever(?))

WarningService: Shutdown: TcpSocketLink OutOfMemory
[20-06-01 13:11:54.045] {EventThread} Task threw exception
java.lang.OutOfMemoryError: GC overhead limit exceeded
at io.socket.engineio.client.Transport.onError(Transport.java:63)
at io.socket.engineio.client.transports.PollingXHR.access$100(PollingXHR.java:26)
at io.socket.engineio.client.transports.PollingXHR$6$1.run(PollingXHR.java:140)
at io.socket.thread.EventThread$2.run(EventThread.java:80)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

[20-06-01 13:11:54.045] {resin-port-8080-38} WarningService: Shutdown: TcpSocketLink OutOfMemory
Exception in thread "EventThread" java.lang.OutOfMemoryError: GC overhead limit exceeded
at io.socket.engineio.client.Transport.onError(Transport.java:63)
at io.socket.engineio.client.transports.PollingXHR.access$100(PollingXHR.java:26)
at io.socket.engineio.client.transports.PollingXHR$6$1.run(PollingXHR.java:140)
at io.socket.thread.EventThread$2.run(EventThread.java:80)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)


It looks like the listener is refusing the connection

Is there something I'm missing??
Is there something your documentation is missing?
Do you have a demonstration example of -say- a simple echo server that you could share?
Some help would be appreciated

Events are not received

We have developed a Java chatroom project that uses this Java library to implement the server and the socket.io java port for the client.

During development we realized that our tests fail randomly for no apparent reason: in fact, just restart them and there is no more failure. Obviously, whenever we were waiting for an event to be received we used a test library that waits for a preset timeout (usually 2 seconds) before failing the tests. This should give the events time to reach the client or the server.

Despite this we concluded that sometimes the events never reach their destination although they have been successfully sent. This happens in both directions: server to client and client to server.

Attached you will find a log of a tests run during which a test fails: test-failure.txt
You can see that at line 23 the server sends the "msg" event but the client does not receive it for the next 2 seconds, so the test fails.
We also tried to increase the timeout (e.g. 20 seconds) but the result is the same: the event is sent but never reaches its destination.

UPDATE:
Here you can find a GitHub Actions workflow in which the problem reoccurred. I don't know why the timestamps are not sorted but you can understand that around line 1750 the server sends the "connected" event which is not received by the client for the next 2 seconds. If we try to restart the workflow, the problem will most likely not occur again.

Is it possible to send messages from one namespace to a different namespace?

currently we are building socket.io server and trying to design an asyncapi spec with two channels /errors and /updates.
The idea is that client will get regular updates on /updates channel and any errors or warnings in a different /errors channel.

The source of errors could be originating from logic on /updates namespace and we are trying to see if its possible to emit a message into /errors namespace from the logic thats inside the .on listner of /updates namespace?

also we observed the socket id is different when we try to connect as a client to both /updates and /errors channels.
are we in the right direction or doing something basically wrong here?

Is it possible to have same socketid or socket for two different namespaces?

Assumption:

  1. we are assuming the channels on asyncapi spec to be analogous to namespace in socket.io

@trinopoty

Parser package conflict when using client in same project

Hi

I created test project to check our use cases with socket.io official client 2.0.1 and socket.io-server-java.

Since following classes with client same package, it causes conflict :(

https://github.com/socketio/engine.io-client-java/blob/master/src/main/java/io/socket/engineio/parser/Parser.java
https://github.com/socketio/engine.io-server-java/blob/master/engine.io-server/src/main/java/io/socket/engineio/parser/Parser.java

Would you consider changing Parser package at server (or client?)

Error stack trace:
java.lang.IncompatibleClassChangeError: Method 'void io.socket.engineio.parser.Parser.decodePayload(java.lang.String, io.socket.engineio.parser.Parser$DecodePayloadCallback)' must be InterfaceMethodref constant
at io.socket.engineio.client.transports.Polling._onData(Polling.java:131)
at io.socket.engineio.client.transports.Polling.onData(Polling.java:101)
at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:117)
at io.socket.thread.EventThread$2.run(EventThread.java:80)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)

Exception in thread "EventThread" java.lang.IncompatibleClassChangeError: Method 'void io.socket.engineio.parser.Parser.decodePayload(java.lang.String, io.socket.engineio.parser.Parser$DecodePayloadCallback)' must be InterfaceMethodref constant
at io.socket.engineio.client.transports.Polling._onData(Polling.java:131)
at io.socket.engineio.client.transports.Polling.onData(Polling.java:101)
at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:117)
at io.socket.thread.EventThread$2.run(EventThread.java:80)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)

Change license to Apache2

This is a issue created for all current contributors to provide their permission to change the license of the repository from MIT to Apache2.

Please state if you're okay or not with changing the license to Apache2.

@oddmario

Namespaces?

Is there an issue with using namespaces other than "/"?

I did not get

The document is not complete.
How do we start a server now ?
How do we specify the IP address and port ?

How to support cross-origin websocket request from 127.0.0.1 with different ports?

I'm using socket.io-server-java in a android app(which means, running it in a background Thread in a Service)
I use the tcp listen port 9999, and setup adb forward:

adb forward tcp:9999 tcp:9999

Then a use a web page client from local host with port 10000, but the web client cannot connect with server side report error:

I/System.out: 400 null HTTP/1.1
I/System.out: Date: Fri, 24 Mar 2023 08:39:51 GMT
I/System.out: Access-Control-Allow-Origin: http://127.0.0.1:10000
I/System.out: Access-Control-Allow-Credentials: true
I/System.out: Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
I/System.out: Access-Control-Allow-Headers: origin, content-type, accept
I/System.out: Content-Type: application/json;charset=utf-8

It seems the cross-origin is not defaultly supported. How can I enable CORS?

Ping-pong response status

Hi @trinopoty

We are not seeing response status either way from server and client. I am sharing few links where the response status is not getting in our socket-io-server. could you please help to me understand whether this can be done from server as server as to send some response pong which is generally 3 as given in the following links :

https://stackoverflow.com/questions/24564877/what-do-these-numbers-mean-in-socket-io-payload
https://github.com/socketio/socket.io-protocol

Unable to connect socket-io with socket-io chrome extension

Hi @trinopoty / @oddmario
I have tried running the demo project - https://github.com/oddmario/socket.io-server-java-demo. I was able to connect to the server with the simple js client as given below
const
io = require("socket.io-client"),
ioClient = io.connect("http://localhost:9094");

ioClient.emit("message","Hello Server");
ioClient.on("message", (msg) => console.info(msg));

It is working fine but when I am trying to connect to the server using web-socket client extension of chrome with the following url
ws://localhost:9094/socket.io/?EIO=4&transport=websocket. I am finding out that the connection is not established and the communication is not happening. Can you please help me out how to enable web socket transport so that the server recognizes the connection as ws (web socket) connection instead of http.

Is there a demo for springboot2.x and tomcat?

I've tried use @WebServlet("/socket.io/*") and @ServletComponentScan in springboot2.x default with tomcat, but I'm too stupid to make it work, I just can't connet to the server. Could you please help me?

BTW, I'm using socket.io-client.js 4.5.2(latest) as client, and it works fine with the jetty demo.

`@WebServlet("/socket.io/*")
public class SocketServlet extends HttpServlet {

private final EngineIoServer mEngineIoServer;
private final SocketIoServer mSocketIoServer;

public SocketServlet() {
    EngineIoServerOptions options = EngineIoServerOptions.newFromDefault();
    options.setAllowedCorsOrigins(null);
    mEngineIoServer = new EngineIoServer(options);
    mSocketIoServer = new SocketIoServer(mEngineIoServer);
    SocketIoNamespace namespace = mSocketIoServer.namespace("/");
    namespace.on("connection", objects -> {
        // do something
    });
}

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    mEngineIoServer.handleRequest(req, resp);
}

}`

SocketIoSocket.send(): should include namespace in packet

Testing scenarios where using a non-default namespace showed that socket.send( ... ) messages were not making it through to the client (or making it through to the browser, but not processed by the js client listeners).

Modifying SocketIoSocket.java$send() to the below resolved for me:

sendPacket(packet);
// instead of
//  mClient.sendPacket(packet);

How does one setup an Acknowledgement function?

Right now I listen for an event the following way:

socket.on("createRoom", msgArgs -> {
                try {
                    log.info("[Client %s] requested room creation".formatted(socket.getId()));
                    Room newRoom = new Room(socket.getId());
                    WebServiceBack.INSTANCE.roomList().put(newRoom.roomId(), newRoom);

                    final var responseObj = new CreateRoomResponsePacket(newRoom.roomId(), socket.getId(), createRoomRequest.name());
                    SocketIoSocket.ReceivedByLocalAcknowledgementCallback.
                    socket.send("createRoom", dataToJson(responseObj));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

How should I setup local ack function in the first place?

Continuous Connection request to server from client.

Hi,

I am using socket.io-server-java on the BE side and socket.io-client on the FE side.

The connection to the socket is working and the communication events between BE and FE are also working.
The problem is that after the client is sending multiple requests to the server repeating the connection.
I know there are closed issues regarding this but nothing related to spring.

Do you know how can I fix this?

Thanks!

image

Ignore the fact that the request is red. The screenshot is from the server environment.

WebSocketsConfiguration.java

package com.example.demo_from_git.config;

import io.socket.engineio.server.EngineIoServer;
import io.socket.socketio.server.SocketIoServer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;


@EnableAutoConfiguration
@ComponentScan({
        "com.example.demo_from_git.config",
        "com.example.demo_from_git.listener",
        "com.example.demo_from_git.servlet"
})
@ServletComponentScan("com.example.demo_from_git.servlet")
public class WebSocketsConfiguration {

    @Bean
    public EngineIoServer getEngineIoServer() {
        return new EngineIoServer();
    }

    @Bean
    public SocketIoServer getSocketIoServer(EngineIoServer engineIoServer) {
        return new SocketIoServer(engineIoServer);
    }

}

SocketIoServlet.java

package com.example.demo_from_git.servlet;

import com.example.demo_from_git.listener.ConnectionListener;
import io.socket.client.Socket;
import io.socket.engineio.server.EngineIoServer;
import io.socket.socketio.server.SocketIoServer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/socket.io/*")
public class SocketIoServlet extends HttpServlet {

    private EngineIoServer engineIoServer;

    private final ConnectionListener connectionListener;

    @Autowired
    public SocketIoServlet(SocketIoServer socketIoServer, EngineIoServer engineIoServer, ConnectionListener connectionListener) {
        this.engineIoServer = engineIoServer;
        this.connectionListener = connectionListener;
        socketIoServer.namespace("/test-socket").on(Socket.EVENT_CONNECT, this.connectionListener);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        engineIoServer.handleRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

ConnectionListener.java

package com.example.demo_from_git.listener;

import io.socket.emitter.Emitter;
import io.socket.socketio.server.SocketIoSocket;
import org.springframework.stereotype.Component;

@Component
public class ConnectionListener implements Emitter.Listener {

    @Override
    public void call(Object... objects) {
        SocketIoSocket socketIoSocket = (SocketIoSocket) objects[0];

        socketIoSocket.send("custom_event", "test socket message");
    }
}

Client.js

const io = require("socket.io-client");

const socket = io.connect('ws://localhost:8080/test-socket')

socket.on("event://get-message", (data) => {
    console.log(data);
});

Android support

Im trying to use library in android but when im connected to server with client and stop of send data, server restart automatically at few seconds.

Broadcasting Java objects

When emitting events with https://github.com/socketio/socket.io-client-java, Java objects (eg. Map) can be sent to server without any JSON conversion. On server side, it is converted to an instance of JSONObject.

But when broadcasting from server, java object isn't allowed. PacketUtils.isPacketDataValid(array) throws error when array contains java objects. It is expecting the literal types or JSONObject/JSONArray. For consistency, should it allow broadcasting Java objects similar to client? Looking at the client's IO Parser, it is doing the same decoding as server. So it should be able to read those objects same way as server.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.