Socket.IO server implemented on Java. Realtime java framework

Overview

Netty-socketio Overview

This project is an open-source Java implementation of Socket.IO server. Based on Netty server framework.

Checkout Demo project

Licensed under the Apache License 2.0.

Features

  • Supports 0.7...0.9.16 (netty-socketio 1.6.6) and 1.0+ (netty-socketio latest version) version of Socket.IO-client
  • Supports xhr-polling transport
  • Supports websocket transport
  • Supports namespaces and rooms
  • Supports ack (acknowledgment of received data)
  • Supports SSL
  • Supports client store (Memory, Redisson, Hazelcast)
  • Supports distributed broadcast across netty-socketio nodes (Redisson, Hazelcast)
  • Supports OSGi
  • Supports Spring
  • Lock-free and thread-safe implementation
  • Declarative handler configuration via annotations

Performance

Customer feedback in 2012:
CentOS, 1 CPU, 4GB RAM runned on VM: CPU 10%, Memory 15%
6000 xhr-long polling sessions or 15000 websockets sessions
4000 messages per second

Customer feedback in 2014:
"To stress test the solution we run 30 000 simultaneous websocket clients and managed to peak at total of about 140 000 messages per second with less than 1 second average delay." (c) Viktor Endersz - Kambi Sports Solutions

Projects using netty-socketio

AVOS Cloud: avoscloud.com
Bingo Crack: bingocrack.com
Kambi Sports Solutions: kambi.com
ARSnova: arsnova.eu
Zipwhip: zipwhip.com

Recent Releases

Please Note: trunk is current development branch.

17-Jan-2020 - version 1.7.18 released

Feature - support for event interceptors which catch all events (thanks to yosiat)
Fixed - namespace event broadcasting (thanks to Volodymyr Masliy)

11-Jan-2019 - version 1.7.17 released

Feature - randomSession setting added to Config object (thanks to yuanxiangz)
Fixed - NPE in WebSocketTransport
Fixed - NPE & memory leak (thanks to zhaolianwang)
Fixed - namespace parsing (thanks to Redliver)
Fixed - Redisson 3.9+ compatibility

06-Jul-2018 - version 1.7.16 released

Fixed - non thread-safe ACK handling (thanks to dawnbreaks)
Fixed - inactive long-polling channels cause memory leak (thanks to dawnbreaks)
Fixed - websocket CloseFrame processing (thanks to hangsu.cho)
Fixed - WebSocketTransport NPE

15-May-2018 - version 1.7.15 released

Fixed - Session ID is not unique anymore
Fixed - fixed underlying connection not closing on ping timeout
Fixed - the "fin_close" problem

26-Feb-2018 - version 1.7.14 released

Feature - added local socket address for the connection (thanks to @SergeyGrigorev)
Feature - addPingListener method added (thanks to @lovebing)
Feature - add ThreadFactory for HashedWheelTimer (thanks to @hand515)
Fixed - changed SO_LINGER to be handled as child channel (not server channel) option (thanks to @robymus)
Fixed - ByteBuf leak if binary attachments are used
Fixed - restore session from Cookie (thanks to @wuxudong)
Fixed - NumberFormatException when b64 is bool value (thanks to @vonway)
Fixed - data encoding for polling transport

20-Sep-2017 - version 1.7.13 released

Feature - Added option to change the SSL KeyFactoryAlgorithm using Configuration (thanks to @robymus)
Improvement - Binary ack handling improvements (thanks to Sergey Bushik)
Fixed - Failed to mark a promise as success because it has succeeded already (thanks to @robymus)

27-Aug-2016 - version 1.7.12 released

Feature - SocketIOServer.removeAllListeners method added
Feature - BroadcastOperations.sendEvent method with excludedClient param added
Improvement - Redisson updated to 2.4.0
Fixed - memory leak in Namespace object (thanks to @CrazyIvan007)

13-Jul-2016 - version 1.7.11 released

Fixed - Throw error if transport not supported
Fixed - Client disconnecting when using Polling - IndexOutOfBoundsException

4-Mar-2016 - version 1.7.10 released

Fixed - netty updated to 4.1.0.CR3 version
Fixed - binary packet parsing (thanks to Winston Li)

6-Feb-2016 - version 1.7.9 released

Feature - Compression support
Fixed - DotNET client request handling
Fixed - Packet length format parsing
Fixed - skipping 'd=' in packet
Fixed - Polling clients sporadically get prematurely disconnected (thanks to lpage30)
Fixed - connections stay open forever if server sent close packet
Fixed - compatibility with Redisson latest version

30-Nov-2015 - version 1.7.8 released

Improvement - WebSocketServerHandshaker.allowExtensions is true now
Improvement - SessionID cookie implementation (thanks to @ryandietrich)
Fixed - clientRooms leak (thanks to @andreaspalm)
Fixed - ExceptionListener not used for errors in JSON parsing
Fixed - "silent channel" attack

26-Mar-2015 - version 1.6.7 released

Improvement - useStrictOrdering param added for websocket packets strict ordering
Improvement - FAIL_ON_EMPTY_BEANS = false option setted in json decoder

18-Feb-2015 - version 1.7.7 released

Improvement - no need to add jackson lib if you use own JsonSupport impl
Fixed - SocketIO client 1.3.x support
Fixed - Charset encoding handling (thanks to alim-akbashev)

17-Jan-2015 - version 1.7.6 released

Improvement - SocketIONamespace.getName() added
Fixed - WebSocket frames aggregation
Fixed - WebSocket buffer release
Fixed - Unexpected end-of-input in VALUE_STRING error
Fixed - Access-Control-Allow-Credentials is TRUE for requests with origin header

05-Dec-2014 - version 1.7.5 released

Feature - Configuration.sslProtocol param added
Fixed - BinaryEvent ack handling
Fixed - BinaryEvent non b64 encoding/decoding
Fixed - buffer leak during packet encoding

15-Nov-2014 - version 1.7.4 released

Fixed - packet encoding
Fixed - BinaryEvent encoding/decoding
Fixed - unchallenged connections handling

29-Sep-2014 - version 1.6.6 released

Feature - origin setting added
Feature - crossDomainPolicy setting added
Feature - SocketIOServer.startAsync method added

24-Sep-2014 - version 1.7.3 released

Feature - Epoll support
Improvement - BinaryEvent support
Fixed - SocketIOClient disconnect handling
Fixed - broadcast callback
Fixed - NPE then no transport defined during auth
Fixed - ping timeout for polling transport
Fixed - buffer leak in PacketEncoder

22-Aug-2014 - version 1.7.2 released

Fixed - wrong outgoing message encoding using websocket transport
Fixed - NPE in websocket transport
Fixed - multiple packet decoding in polling transport
Fixed - buffer leak

07-Jul-2014 - version 1.7.1 released

Feature - ability to set custom Access-Control-Allow-Origin via Configuration.origin
Fixed - connection via CLI socket.io-client

28-Jun-2014 - version 1.7.0 released

Feature - Socket.IO 1.0 protocol support. Thanks to the new protocol decoding/encoding has speedup
Dropped - SocketIOClient.sendMessage, SocketIOClient.sendJsonObject methods and corresponding listeners
Dropped - Flashsocket transport support
Dropped - protocol version 0.7 ... 0.9.16

13-May-2014 - version 1.6.5 released

Improvement - single packet encoding optimized, used mostly in WebSocket transport. Encoding time reduced up to 40% (thanks to Viktor Endersz)
Improvement - rooms handling optimized
Improvement - ExceptionListener.exceptionCaught method added
Breaking api change - Configuration.autoAck replaced with ackMode
Feature - trustStore setting added
Feature - maxFramePayloadLength setting added
Feature - getAllClients and getClient methods added to SocketIONamespace
Fixed - SocketIOServer.getAllClients returns wrong clients amount

25-Mar-2014 - version 1.6.4 released

Fixed - message release problem
Fixed - problem with exception listener configuration redefinition
Breaking api change - DataListener.onData now throws Exception
Improvement - data parameter added to exception listener
Improvement - ability to setup socket configuration
Improvement - Configuration.autoAck parameter added

06-Mar-2014 - version 1.6.3 released

Fixed - AckCallback handling during client disconnect
Fixed - unauthorized handshake HTTP code changed to 401
Breaking api change - Configuration.heartbeatThreadPoolSize setting removed
Feature - annotated Spring beans support via SpringAnnotationScanner
Feature - common exception listener
Improvement - ScheduledExecutorService replaced with HashedWheelTimer

08-Feb-2014 - version 1.6.2 released

Fixed - wrong namespace client disconnect handling
Fixed - exception in onConnect/onDisconnect/isAuthorized methods leads to server hang
Breaking api change - SocketIOClient.sendEvent methods signature changed
Improvement - multi type events support via MultiTypeEventListener and OnEvent annotation
Improvement - multi type events ack support via MultiTypeAckCallback
Improvement - SocketIOClient.getHandshakeData method added
Improvement - Jedis replaced with Redisson

14-Jan-2014 - version 1.6.1 released

Fixed - JDK 1.6+ compatibility
Feature - authorization support

19-Dec-2013 - version 1.6.0 released

Fixed - XHR-pooling transport regression
Fixed - Websocket transport regression
Fixed - namespace NPE in PacketHandler
Fixed - executors shutdown during server stop
Feature - client store (Memory, Redis, Hazelcast) support
Feature - distributed broadcast across netty-socketio nodes (Redis, Hazelcast) support
Feature - OSGi support (thanks to rdevera)
Improvement - XHR-pooling optimization
Improvement - SocketIOClient.getAllRooms method added

07-Dec-2013 - version 1.5.4 released

Fixed - flash policy "request leak" after page reload (thanks to ntrp)
Fixed - websocket swf loading (thanks to ntrp)
Fixed - wrong urls causes a potential DDoS
Fixed - Event.class package visibility changed to avoid direct usage
Improvement - Simplified Jackson modules registration

24-Oct-2013 - version 1.5.2 released

Fixed - NPE during shutdown
Improvement - isEmpty method added to Namespace

13-Oct-2013 - version 1.5.1 released

Fixed - wrong ack timeout callback invocation
Fixed - bigdecimal serialization for JSON
Fixed - infinity loop during packet handling exception
Fixed - 'client not found' handling

27-Aug-2013 - version 1.5.0 released

Improvement - encoding buffers allocation optimization.
Improvement - encoding buffers now pooled in memory to reduce GC pressure (netty 4.x feature).

03-Aug-2013 - version 1.0.1 released

Fixed - error on unknown property during deserialization.
Fixed - memory leak in long polling transport.
Improvement - logging error info with inbound data.

07-Jun-2013 - version 1.0.0 released

First stable release.

Maven

Include the following to your dependency list:

<dependency>
 <groupId>com.corundumstudio.socketio</groupId>
 <artifactId>netty-socketio</artifactId>
 <version>1.7.12</version>
</dependency>

Supported by

YourKit is kindly supporting this open source project with its full-featured Java Profiler. YourKit, LLC is the creator of innovative and intelligent tools for profiling Java and .NET applications. Take a look at YourKit's leading software products: YourKit Java Profiler and YourKit .NET Profiler.

Comments
  • 1.7.3 leak memory && Unexpected end-of-input in VALUE_STRING

    1.7.3 leak memory && Unexpected end-of-input in VALUE_STRING

    Hi. I use a framework(1.7.3 version) already some time and I have accumulated a number of issues:).

    1. Memory leak when loading Blobs: ServerSIde
    public class FileDTO {
        private byte[] data;
        public FileDTO(int id, byte[] data, String error, String key, String name, String sql) {
            super();
           ...
            this.data = data;
           ...
        }
        ...
    }
    
    public class Launcher {
      public static void main(String[] args) throws InterruptedException {
    ...
      Configuration config = new Configuration();
            config.setHostname("192.168.0.34");
            config.setPort(3000);
            config.setMaxFramePayloadLength(10000000);
            config.setMaxHttpContentLength(10000000);
            final SocketIOServer server = new SocketIOServer(config);
    
    ....
     }
    ....
      server.addEventListener("fileUpload", FileDTO.class, new DataListener<FileDTO>() {
                Connection conn = new WebService();
                @Override
                public void onData(SocketIOClient client, FileDTO data, AckRequest ackRequest) {
                   //code for upload file
                }
            });
    }
    

    Client Side

    socket.emit('fileUpload', {
      data: base64Data
    ..
    })
    

    Problem: when I upload a large file( ~150+kb ), the server generates an error

    type: class com.corundumstudio.socketio.protocol.Event
    com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input in VALUE_STRING
     at [Source: io.netty.buffer.ByteBufInputStream@25f5445b; line: 1, column: 129893]
            at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1419)
            at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:508)
            at com.fasterxml.jackson.core.base.ParserMinimalBase._reportInvalidEOF(ParserMinimalBase.java:445)
            at com.fasterxml.jackson.core.base.ParserMinimalBase._reportInvalidEOF(ParserMinimalBase.java:441)
            at com.fasterxml.jackson.core.base.ParserBase.loadMoreGuaranteed(ParserBase.java:408)
            at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._finishString2(UTF8StreamJsonParser.java:2184)
            at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._finishString(UTF8StreamJsonParser.java:2165)
            at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.getText(UTF8StreamJsonParser.java:279)
            at com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:224)
            at com.fasterxml.jackson.databind.deser.std.BaseNodeDeserializer.deserializeArray(JsonNodeDeserializer.java:262)
            at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:64)
            at com.fasterxml.jackson.databind.deser.std.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:14)
            at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3023)
            at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:1705)
            at com.corundumstudio.socketio.protocol.JacksonJsonSupport$EventDeserializer.deserialize(JacksonJsonSupport.java:140)
            at com.corundumstudio.socketio.protocol.JacksonJsonSupport$EventDeserializer.deserialize(JacksonJsonSupport.java:126)
            at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3051)
            at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2192)
            at com.corundumstudio.socketio.protocol.JacksonJsonSupport.readValue(JacksonJsonSupport.java:223)
            at com.corundumstudio.socketio.JsonSupportWrapper.readValue(JsonSupportWrapper.java:55)
            at com.corundumstudio.socketio.protocol.PacketDecoder.decode(PacketDecoder.java:180)
            at com.corundumstudio.socketio.protocol.PacketDecoder.decodePackets(PacketDecoder.java:118)
            at com.corundumstudio.socketio.handler.InPacketHandler.channelRead0(InPacketHandler.java:65)
            at com.corundumstudio.socketio.handler.InPacketHandler.channelRead0(InPacketHandler.java:36)
            at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:168)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
            at com.corundumstudio.socketio.transport.WebSocketTransport.channelRead(WebSocketTransport.java:92)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at com.corundumstudio.socketio.transport.PollingTransport.channelRead(PollingTransport.java:109)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at com.corundumstudio.socketio.handler.AuthorizeHandler.channelRead(AuthorizeHandler.java:115)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:108)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:163)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
            at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:130)
            at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
            at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
            at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
            at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
            at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
            at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
            at java.lang.Thread.run(Thread.java:745)
    [nioEventLoopGroup-3-8] ERROR com.corundumstudio.socketio.handler.InPacketHandler - Error during data processing. Client sessionId: 3b89da4b-d899-4399-9a32-2d93236b1ad3, data:
    java.lang.NullPointerException
            at com.corundumstudio.socketio.protocol.PacketDecoder.decode(PacketDecoder.java:181)
            at com.corundumstudio.socketio.protocol.PacketDecoder.decodePackets(PacketDecoder.java:118)
            at com.corundumstudio.socketio.handler.InPacketHandler.channelRead0(InPacketHandler.java:65)
            at com.corundumstudio.socketio.handler.InPacketHandler.channelRead0(InPacketHandler.java:36)
            at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:168)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
            at com.corundumstudio.socketio.transport.WebSocketTransport.channelRead(WebSocketTransport.java:92)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at com.corundumstudio.socketio.transport.PollingTransport.channelRead(PollingTransport.java:109)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at com.corundumstudio.socketio.handler.AuthorizeHandler.channelRead(AuthorizeHandler.java:115)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:108)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:163)
            at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:333)
            at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:319)
            at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:787)
            at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:130)
            at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
            at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
            at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
            at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
            at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116)
            at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
            at java.lang.Thread.run(Thread.java:745)
    

    a) How can I fix this error? b) If several times to upload a large file (2mb) in different pages, server crashes:

    [nioEventLoopGroup-3-8] ERROR io.netty.util.ResourceLeakDetector - LEAK: ByteBuf.release() 
    was not called before it's garbage-collected. 
    Enable advanced leak reporting to find out where the leak occurred. 
    To enable advanced leak reporting, specify the JVM option 
    '-Dio.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel()
    

    How can I avoid it?

    bug 
    opened by tselishev-semen 32
  • Binary / byte array messages broken.

    Binary / byte array messages broken.

    Thanks for this awesome framework. I was excited to add the binary support to our product. The problem is I can't get the basic byte[] pushed down based on the demo.

    I'm using 1.7.5 (and even tried snapshot). The BinaryEventLauncher and corresponding binary-event-index.html page.

    1. The client on 'msg' doesn't get invoked unless I use Byte[](instead of the demo code that has byte[]) on the server side. I wouldn't think this matters but for some reason it does. SERVER SIDE BELOW

    2. Even when the client gets called back it throws an "Uncaught RangeError: Invalid typed array length" exception when constructing the Uint8Array(file). CLIENT SIDE BELOW

    SERVER SIDE server.addEventListener("msg", Byte[].class, new DataListener<Byte[]>() { @Override public void onData(SocketIOClient client, Byte[] data, AckRequest ackRequest) {

                //client.sendEvent("msg", data);
                ((ClientOperations) client).sendEvent("msg", data);
            }
        });
    

    CLIENT SIDE (Copied from demo) socket.on('msg', function(file) {

                      var arrayBuffer = new Uint8Array(file).buffer;
                      var blob        = new Blob([arrayBuffer]);
    
                      var imgList = $('ul#img-list');
    
                      var li = $('<li/>').appendTo(imgList);
                      $('<div/>').text(file.name).appendTo(li);
                      var img = $('<img/>').appendTo(li);
    
                      var reader = new FileReader();
                      reader.onload = (function(aImg) {
                        return function(e) {
                          aImg.attr('src', e.target.result);
                          aImg.attr('width', 150);
                        };
                      })(img);
    
                      reader.readAsDataURL(blob);
        });
    
    bug 
    opened by jimmyryan15 31
  • Pooling connections which never timeout

    Pooling connections which never timeout

    Hi, I have problem with connections which stay at transport pooling and never switch to websocket transport.

    If browser have problem with CORS, then I have for 1 user hundreds of connections which never timeout. :/ The connection stay in this state: isChannelOpen:false, getTransport:POLLING.

    You can simulate this problem by CURL - just create a 1. request to socket IO server:

    curl --connect-timeout 2 -L 'http://myserver.com:20443/socket.io/?myparam1=XY&myparam2=123&EIO=2&transport=polling&t=1407835214929-0' > /dev/null
    

    Then when you check connected clients, this connection never timeout :/ This causes, that my socketIO server once a day run out of memory :/

    I found that problem with CORS has only a few of FireFox users. And usually thay have opened FF many days. I didn't find why they have problem with CORS. I will check it. But the main problem are the connections which never timeout :(

    This is a log from browser, where you can see, that connection to "myserver.com" timeout, but the connection on server was created.

    "socket.io-client:url parse http://myserver.com:20443 +0ms" socket.io.js:1258
    "socket.io-client new io instance for http://myserver.com:20443 +0ms" socket.io.js:1258
    "socket.io-client:manager readyState closed +0ms" socket.io.js:1258
    "socket.io-client:manager opening http://myserver.com:20443 +0ms" socket.io.js:1258
    "engine.io-client:socket creating transport "polling" +0ms" socket.io.js:1258
    "engine.io-client:polling polling +0ms" socket.io.js:1258
    "engine.io-client:polling-xhr xhr poll +0ms" socket.io.js:1258
    "engine.io-client:polling-xhr xhr open GET: http://myserver.com:20443/socket.io/?nl_user_id=1286029&nl_phone_extension=20931&EIO=2&transport=polling&t=1409054107046-0 +0ms" socket.io.js:1258
    "engine.io-client:polling-xhr xhr data null +0ms" socket.io.js:1258
    "engine.io-client:socket setting transport polling +2ms" socket.io.js:1258
    "socket.io-client:manager connect attempt will timeout after 20000 +3ms" socket.io.js:1258
    "socket.io-client:manager readyState opening +0ms" socket.io.js:1258
    "socket.io-client:manager connect attempt timed out after 20000 +20s" socket.io.js:1258
    "engine.io-client:socket socket close with reason: "forced close" +20s" socket.io.js:1258
    "engine.io-client:polling transport not open - deferring close +20s" socket.io.js:1258
    "engine.io-client:socket socket closing - telling transport to close +1ms" socket.io.js:1258
    "socket.io-client:manager connect_error +3ms" socket.io.js:1258
    "socket.io-client:manager will wait 1000ms before reconnect attempt +0ms" socket.io.js:1258
    "socket.io-client:manager attempting reconnect +1s" socket.io.js:1258
    "socket.io-client:manager readyState closed +0ms" socket.io.js:1258
    "socket.io-client:manager opening http://myserver.com:20443 +0ms" socket.io.js:1258
    "engine.io-client:socket creating transport "polling" +1s" socket.io.js:1258
    "engine.io-client:polling polling +1s" socket.io.js:1258
    "engine.io-client:polling-xhr xhr poll +21s" socket.io.js:1258
    "engine.io-client:polling-xhr xhr open GET: http://myserver.com:20443/socket.io/?myparam1=XY&myparam2&EIO=2&transport=polling&t=1409054128094-1 +1ms" socket.io.js:1258
    "engine.io-client:polling-xhr xhr data null +0ms" socket.io.js:1258
    "engine.io-client:socket setting transport polling +2ms" socket.io.js:1258
    "socket.io-client:manager connect attempt will timeout after 20000 +3ms"
    
    bug 
    opened by dawe7 26
  • memory leak

    memory leak

    i use netty-socketio 1.6.5 . i found a memory leak ,com.corundumstudio.socketio.transport.XHRPollingClient has not be GC. i use Eclipse Memory Analyzer ,the description is: One instance of "com.corundumstudio.socketio.transport.XHRPollingClient" loaded by "sun.misc.Launcher$AppClassLoader @ 0x7000b7678" occupies 342,686,224 (59.63%) bytes. image

    opened by topiman 25
  • flashsocket transport on IE

    flashsocket transport on IE

    How do I enable flash socket transport? I have already set my server add flash socket transport but my client in IE9 cant still connect. What do i need to set in client?

    improvement 
    opened by ilaganra 20
  • Cannot find in maven public repos

    Cannot find in maven public repos

    Hello!

    First of all, thank you for your great work!

    I have a question: is your library available in maven public repositories? I've failed to find it there.

    If yes, could you provide me an address of the repository?

    And if no, could you please publish it?

    opened by deinlandel 20
  • No connect packet returned for polling client, 1.7.0

    No connect packet returned for polling client, 1.7.0

    I'm testing netty-socketio with SocketIO-client 1.0.6, polling transport. The client never gets notification for connect. Then I found the server doesn't send connect packet to client.

    From code, I found it runs into the null block of ClientHead.java:

        public ChannelFuture send(Packet packet, Transport transport) {
            TransportState state = channels.get(transport);
            state.getPacketsQueue().add(packet);
    
            Channel channel = state.getChannel();
            if (channel == null
                    || (transport == Transport.POLLING && channel.attr(EncoderHandler.WRITE_ONCE).get() != null)) {
               // run into the null block
                return null;
            }
            return sendPackets(transport, channel);
        }
    

    Could you please take a look if there's anything wrong ?

    bug 
    opened by sunng87 19
  • PacketEncoder corrupts UTF-8 message

    PacketEncoder corrupts UTF-8 message

    Hi,

    Using SocketIOClient.send("русский"), I receive on client string "русский"

    I think that the problem is in PacketEncoder lines 272-274:

                                String str = b.toString(CharsetUtil.ISO_8859_1);
                                if (enc.canEncode(str)) {
                                    buf.writeBytes(str.getBytes(CharsetUtil.UTF_8));
                                }
    

    the string gets corrupted when converting it with ISO_8859_1 charset, and then it is sent corrupted

    bug 
    opened by evgeny-pasynkov 18
  • have problem with integration with spring?

    have problem with integration with spring?

    I just want to start the netty-socketio server(I use netty-socketio 1.6.0) from a spring service. this code is just have a simple copy from (github:netty-socketio-demo). bean "socketIOConfiguration" is configed by xml file。 when start my project from eclipse .I can find log "SocketIO server started at port: 9092" and show "Client has connected to the server!" from the html demo page(it is also used the netty-socketio-demo index.htm"). and when I send some words from web client page. the server side has no any action found and not send back the words to web client page. I don't know what cause it, please help.thanks very much.

    @Service public class SocketIOService implements Runnable { Configuration config = SpringUtils.getBean("socketIOConfiguration"); SocketIOServer server = new SocketIOServer(config); public SocketIOService() { server.addJsonObjectListener(ChatObject.class, new DataListener() { @Override public void onData(SocketIOClient client, ChatObject data, AckRequest ackRequest) { // broadcast messages to all clients server.getBroadcastOperations().sendJsonObject(data); } }); new Thread(this).start(); } public void run(){ server.start(); }

    }

    <!-- config netty-socketio  -->
    <bean id="socketIOConfiguration" class="com.corundumstudio.socketio.Configuration">
        <property name="hostname" value="localhost" />
        <property name="port" value="9092" />    
    </bean>
    
    opened by ashengwang 18
  • Upgrading from 1.7.5 to 1.7.10

    Upgrading from 1.7.5 to 1.7.10

    Hi,

    I was using the 1.7.5 server and wanted to upgrade to 1.7.10. After the upgrade, the connect() call from the client is not completing at all.

    Downgrading to 1.7.5 works fine with the same client.

    I am setting up the server by following the code examples in the project:

    Configuration socketIOConfig = new Configuration();
    socketIOConfig.setPort(9080);
    socketIOConfig.setPreferDirectBuffer(false);            
    SocketIOServer server = new SocketIOServer(socketIOConfig);  
    

    On the server side, I see the "connect" event listener is being called. But the client does not receive any response.

    Are there any changes in the server side that needs to be made? Will the latest 1.7.10 work with 0.9 clients?

    opened by pramodbms 17
  • Outgoing UTF-8 messages are not encoded properly

    Outgoing UTF-8 messages are not encoded properly

    Related to issue #157.

    When sending an object using SocketIOClient.sendEvent(String, Object) class, the resulted JSON payload is not encoded properly.

    If the object contains for example String member with data "русский", the data sent to network is "русский".

    Code used:

    public static class Test { private String data = "русский";

    public String getData() { return data; }

    public void setData(String data) { this.data = data; } }

    Test test = new Test(); test.setData("русский"); client.sendEvent("name", test);

    Resulting JSON payload send to the receiving side: {data:"\xD1\x80\xD1\x83\xD1\x81\xD1\x81\xD0\xBA\xD0\xB8\xD0\xB9"} which is incorrect.

    opened by karhuan 17
  • websocket Abnormal connection

    websocket Abnormal connection

    [nioEventLoopGroup-3-13] ERROR com.corundumstudio.socketio.listener. DefaultExceptionListener - The software in your host has aborted an established connection. java.io. IOException: The software in your host has aborted an established connection. at sun.nio.ch.SocketDispatcher. read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) at sun.nio.ch.IOUtil.read(IOUtil.java:192) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:378) at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:447) at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:881) at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:225) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:748) [nioEventLoopGroup-3-11] ERROR com.corundumstudio.socketio.listener. DefaultExceptionListener - The remote host forced an existing connection to close. java.io. IOException: The remote host forced an existing connection to be closed. at sun.nio.ch.SocketDispatcher. read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) at sun.nio.ch.IOUtil.read(IOUtil.java:192) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:378) at io.netty.buffer.UnpooledUnsafeDirectByteBuf.setBytes(UnpooledUnsafeDirectByteBuf.java:447) at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:881) at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:225) at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354) at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:116) at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137) at java.lang.Thread.run(Thread.java:748)

    image image
    opened by dome661314 0
  • socket.io-client&netty-socketio compatibility issues

    socket.io-client&netty-socketio compatibility issues

    netty-socketio It seems like not supported socket.io v4.5.3, front:

    import {io} from "socket.io-client";
    
    const socket = io("http://localhost:5432");
    
    socket.on("connect", () => {
      console.log(">>>>>>>>>>>>>>success");
    });
    socket.on("join", (val) => {
      console.log("joinData",val);
    });
    

    back:

    @Override
        public void start() throws Exception {
            // Listen for client connection behavior
            socketIOServer.addConnectListener(client -> {
                String loginUserNum = getParamsByClient(client);
                if (loginUserNum != null) {
                    clientMap.put(loginUserNum, client);
                    log.info("user{}joined,online:{}people",loginUserNum,clientMap.size());
                    client.sendEvent("join","i'm Server,Hello Client!");
                }
            });
            socketIOServer.addDisconnectListener(client -> {
                String loginUserNum = getParamsByClient(client);
                if (loginUserNum != null) {
                    clientMap.remove(loginUserNum);
                    client.disconnect();
                }
            });
            socketIOServer.start();
        }
    

    The result is infinite polling, but still not connecting

    opened by Javaismine 2
  • update 1.7.22  connect and disconnect events cannot be accessed by aop

    update 1.7.22 connect and disconnect events cannot be accessed by aop

    I added a custom annotation to the connect event to intercept it, but it did not take effect, which is normal in 1.7.19,Check code found 1.7.22 SpringAnnotationScanner postProcessAfterInitialization and postProcessBeforeInitialization method has made the changes, Is this a bug?

     @OnConnect
      // customer annotation
      @EventCallbackAnnotation(eventName = "connect")
        public void connect(SocketIOClient client) throws InterruptedException {
            log.info("有新客户端连接sessionId:{}", client.getSessionId().toString());
        }
    
    1.7.22 SpringAnnotationScanner class
      public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (this.originalBeanClass != null) {
                this.socketIOServer.addListeners(this.originalBean, this.originalBeanClass);
                log.info("{} bean listeners added", this.originalBeanName);
                this.originalBeanClass = null;
                this.originalBeanName = null;
            }
    
            return bean;
        }
    
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            final AtomicBoolean add = new AtomicBoolean();
            ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() {
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    add.set(true);
                }
            }, new MethodFilter() {
                public boolean matches(Method method) {
                    Iterator var2 = SpringAnnotationScanner.this.annotations.iterator();
    
                    Class annotationClass;
                    do {
                        if (!var2.hasNext()) {
                            return false;
                        }
    
                        annotationClass = (Class)var2.next();
                    } while(!method.isAnnotationPresent(annotationClass));
    
                    return true;
                }
            });
            if (add.get()) {
                this.originalBeanClass = bean.getClass();
                this.originalBean = bean;
                this.originalBeanName = beanName;
            }
    
            return bean;
        }
    

    this.originalBean storage is the original Object, postProcessAfterInitialization (Object beans, String beanName) USES the bean originalBean without using a proxy Object, Disabling aop

    1.7.19 version is normal

     @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            if (originalBeanClass != null) {
                socketIOServer.addListeners(bean, originalBeanClass);
                log.info("{} bean listeners added", beanName);
                originalBeanClass = null;
            }
            return bean;
        }
    
    
    
    opened by y-ywl 0
  • auto disconnected after update to 1.7.22

    auto disconnected after update to 1.7.22

    I'm not sure if this is a bug. With server 1.7.22, and socket.io-client 2.5.0, the server auto disconnect with client because of ping timeout.(this works fine with server version 1.7.21)

    Also this can be reproduce on your demo project: image

    BTW: It says that 1.7.22 supports for the v4 ping/pong mechanism, is that means I can use socket.io-client 4.x? I'v tried so but I got this error: It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)

    opened by jptangchina 4
  • upgrading from polling to websocket to establish a connection with the backend, causing the problem of duplicate sessionId

    upgrading from polling to websocket to establish a connection with the backend, causing the problem of duplicate sessionId

    If the front end js first initiates polling requests, and then upgrades to websocket, the polling request will first generate a UUID as the sessionId, which will be added to the io field of the cookie. No matter how many connections are established later, the sessionId will be the cookie The value of io, which will cause the new connection to knock off the old one. The same browser cannot have multiple connections at the same time. I don't know whether the framework is designed in this way and has such a usage scenario, or is it a bug? Code location: 1.AuthorizeHandler.generateOrGetSessionIdFromRequest(HttpHeaders headers); (Line 245) 2.EncoderHandler.sendMessage(); (Line 141)

    opened by cunyouchen 3
Releases(netty-socketio-1.7.22)
  • netty-socketio-1.7.22(Sep 22, 2022)

  • netty-socketio-1.7.21(Sep 6, 2022)

  • netty-socketio-1.7.18(Jun 11, 2020)

    Feature - support for event interceptors which catch all events (thanks to yosiat) Fixed - namespace event broadcasting (thanks to Volodymyr Masliy)

    Source code(tar.gz)
    Source code(zip)
  • netty-socketio-1.7.17(Jan 11, 2019)

    Feature - randomSession setting added to Config object (thanks to yuanxiangz) Fixed - NPE in WebSocketTransport Fixed - NPE & memory leak (thanks to zhaolianwang) Fixed - namespace parsing (thanks to Redliver) Fixed - Redisson 3.9+ compatibility

    Source code(tar.gz)
    Source code(zip)
  • netty-socketio-1.7.14(Feb 26, 2018)

    Feature - added local socket address for the connection (thanks to @SergeyGrigorev)
    Feature - addPingListener method added (thanks to @lovebing)
    Feature - add ThreadFactory for HashedWheelTimer (thanks to @hand515)
    Fixed - changed SO_LINGER to be handled as child channel (not server channel) option (thanks to @robymus)
    Fixed - ByteBuf leak if binary attachments are used
    Fixed - restore session from Cookie (thanks to @wuxudong)
    Fixed - NumberFormatException when b64 is bool value (thanks to @vonway)
    Fixed - data encoding for polling transport

    Source code(tar.gz)
    Source code(zip)
Owner
Nikita Koksharov
Founder and Lead Developer
Nikita Koksharov
Realtime Client Server Framework for the JVM, supporting WebSockets with Cross-Browser Fallbacks

Welcome to Atmosphere: The Event Driven Framework supporting WebSocket and HTTP The Atmosphere Framework contains client and server side components fo

Atmosphere Framework 3.6k Jan 3, 2023
A Java library that implements a ByteChannel interface over SSLEngine, enabling easy-to-use (socket-like) TLS for Java applications.

TLS Channel TLS Channel is a library that implements a ByteChannel interface over a TLS (Transport Layer Security) connection. It delegates all crypto

Mariano Barrios 149 Dec 31, 2022
jRT measures the response time of a java application to socket-based requests

jRT Version: 0.0.1 jRT is a instrumentation tool that logs and records networking I/O operations "response times" (applicaion response time if be corr

null 45 May 19, 2022
Socket.IO Client Implementation in Java

Socket.IO-Client for Java socket.io-java-client is an easy to use implementation of socket.io for Java. It uses Weberknecht as transport backend, but

Enno Boland 946 Dec 21, 2022
An netty based asynchronous socket library for benchion java applications

Benchion Sockets Library An netty based asynchronous socket library for benchion java applications ?? Documents ?? Report Bug · Request Feature Conten

Fitchle 3 Dec 25, 2022
This is library that look like Scarlet Wrapper Socket.io

This is library that look like Scarlet Wrapper Socket.io

Adkhambek 8 Jan 2, 2023
A simple Socket program with GUI.

Socket A simple Socket program with GUI (by using swing). Suggest to open the folder 'Socket'(TCP) or 'SocketUDP' with IDEA There're 2 methods to run

Lu Yang 2 Sep 21, 2022
A simple Discord bot, which shows the server status of the Lost Ark server Beatrice

Beatrice A simple Discord bot, which shows the server status of the Lost Ark server Beatrice. Example Usage Clone the repository. Edit the property fi

Leon 3 Mar 9, 2022
TCP/UDP client/server library for Java, based on Kryo

KryoNet can be downloaded on the releases page. Please use the KryoNet discussion group for support. Overview KryoNet is a Java library that provides

Esoteric Software 1.7k Jan 2, 2023
A barebones WebSocket client and server implementation written in 100% Java.

Java WebSockets This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are imple

Nathan Rajlich 9.5k Dec 30, 2022
A Java event based WebSocket and HTTP server

Webbit - A Java event based WebSocket and HTTP server Getting it Prebuilt JARs are available from the central Maven repository or the Sonatype Maven r

null 808 Dec 23, 2022
HTTP Server Model made in java

SimplyJServer HTTP Server Model made in java Features Fast : SimplyJServer is 40%-60% faster than Apache, due to it's simplicity. Simple to implement

Praudyogikee for Advanced Technology 2 Sep 25, 2021
A small java project consisting of Client and Server, that communicate via TCP/UDP protocols.

Ninja Battle A small java project consisting of Client and Server, that communicate via TCP/UDP protocols. Client The client is equipped with a menu i

Steliyan Dobrev 2 Jan 14, 2022
Microhttp - a fast, scalable, event-driven, self-contained Java web server

Microhttp is a fast, scalable, event-driven, self-contained Java web server that is small enough for a programmer to understand and reason about.

Elliot Barlas 450 Dec 23, 2022
FileServer - A multithreaded client-server program that uses Java Sockets to establish TCP/IP connection

A multithreaded client-server program that uses Java Sockets to establish TCP/IP connection. The server allows multiple clients to upload, retrieve and delete files on/from the server.

Lokesh Bisht 3 Nov 13, 2022
BAIN Social is a Fully Decentralized Server/client system that utilizes Concepts pioneered by I2P, ToR, and PGP to create a system which bypasses singular hosts for data while keeping that data secure.

SYNOPSIS ---------------------------------------------------------------------------------------------------- Welcome to B.A.I.N - Barren's A.I. Natio

Barren A.I. Wolfsbane 14 Jan 11, 2022
Book Finder application is a client-server application (gRPC) for educational purposes.

Book-Finder Book Finder application is a client-server application (gRPC) for educational purposes. Instalation These projects (Client/Server) are Mav

Mihai-Lucian Rîtan 21 Oct 27, 2022
Check the connectivity of a server with this API.

ServerStatusAPI Presentation : This is a java API with which can test the conectivity of server (all server but you can also use for minecraft). The f

Gabriel MERCIER 1 Mar 16, 2022
WebSocket server with creatable/joinable channels.

bytesocks ?? bytesocks is a WebSocket server which allows clients to create "channels" and send messages in them. It's effectively an add-on for byteb

lucko 6 Nov 29, 2022