├── .gitignore ├── header.txt └── src ├── main └── java │ └── com │ └── corundumstudio │ └── socketio │ ├── DisconnectableHub.java │ ├── store │ ├── pubsub │ │ ├── PubSubListener.java │ │ ├── PubSubType.java │ │ ├── PubSubStore.java │ │ ├── PubSubMessage.java │ │ ├── ConnectMessage.java │ │ ├── DisconnectMessage.java │ │ ├── JoinLeaveMessage.java │ │ ├── DispatchMessage.java │ │ └── BaseStoreFactory.java │ ├── Store.java │ ├── MemoryStore.java │ ├── MemoryPubSubStore.java │ ├── StoreFactory.java │ ├── RedissonStore.java │ ├── HazelcastStore.java │ ├── MemoryStoreFactory.java │ ├── RedissonStoreFactory.java │ ├── HazelcastStoreFactory.java │ ├── RedissonPubSubStore.java │ └── HazelcastPubSubStore.java │ ├── Disconnectable.java │ ├── listener │ ├── ConnectListener.java │ ├── DisconnectListener.java │ ├── MultiTypeEventListener.java │ ├── DataListener.java │ ├── ExceptionListener.java │ ├── ClientListeners.java │ ├── ExceptionListenerAdapter.java │ └── DefaultExceptionListener.java │ ├── messages │ ├── XHRPostMessage.java │ ├── XHROptionsMessage.java │ ├── HttpErrorMessage.java │ ├── HttpMessage.java │ ├── OutPacketMessage.java │ └── PacketsMessage.java │ ├── transport │ ├── BaseTransport.java │ └── NamespaceClient.java │ ├── protocol │ ├── AckArgs.java │ ├── Event.java │ ├── AuthPacket.java │ ├── JsonSupport.java │ ├── PacketType.java │ ├── Packet.java │ └── UTF8CharsScanner.java │ ├── AuthorizationListener.java │ ├── handler │ ├── SuccessAuthorizationListener.java │ ├── SocketIOException.java │ ├── TransportState.java │ ├── ClientsBox.java │ ├── WrongUrlHandler.java │ ├── PacketListener.java │ └── InPacketHandler.java │ ├── annotation │ ├── AnnotationScanner.java │ ├── OnConnect.java │ ├── OnDisconnect.java │ ├── OnEvent.java │ ├── OnConnectScanner.java │ ├── OnDisconnectScanner.java │ ├── SpringAnnotationScanner.java │ ├── ScannerEngine.java │ └── OnEventScanner.java │ ├── MultiTypeAckCallback.java │ ├── VoidAckCallback.java │ ├── AckMode.java │ ├── scheduler │ ├── CancelableScheduler.java │ ├── SchedulerKey.java │ ├── HashedWheelScheduler.java │ └── HashedWheelTimeoutScheduler.java │ ├── namespace │ ├── EventEntry.java │ └── NamespacesHub.java │ ├── ClientOperations.java │ ├── SocketIONamespace.java │ ├── Transport.java │ ├── misc │ ├── IterableCollection.java │ └── CompositeIterable.java │ ├── ack │ ├── AckSchedulerKey.java │ └── AckManager.java │ ├── MultiTypeArgs.java │ ├── BroadcastAckCallback.java │ ├── AckCallback.java │ ├── SocketConfig.java │ ├── SocketIOClient.java │ ├── JsonSupportWrapper.java │ ├── AckRequest.java │ ├── HandshakeData.java │ └── BroadcastOperations.java └── test └── java └── com └── corundumstudio └── socketio ├── parser ├── EncoderBaseTest.java ├── DecoderBaseTest.java ├── EncoderAckPacketTest.java ├── EncoderMessagePacketTest.java ├── DecoderJsonPacketTest.java ├── DecoderMessagePacketTest.java ├── DecoderConnectionPacketTest.java ├── EncoderEventPacketTest.java ├── DecoderAckPacketTest.java ├── EncoderConnectionPacketTest.java ├── DecoderEventPacketTest.java └── PayloadTest.java └── JoinIteratorsTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /.settings 3 | /.classpath 4 | /.project 5 | /target 6 | 7 | /gnupg 8 | -------------------------------------------------------------------------------- /header.txt: -------------------------------------------------------------------------------- 1 | Copyright 2012 Nikita Koksharov 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/DisconnectableHub.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | public interface DisconnectableHub extends Disconnectable { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/PubSubListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | 19 | public interface PubSubListener { 20 | 21 | void onMessage(T data); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/Disconnectable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import com.corundumstudio.socketio.handler.ClientHead; 19 | 20 | 21 | 22 | public interface Disconnectable { 23 | 24 | void onDisconnect(ClientHead client); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/ConnectListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import com.corundumstudio.socketio.SocketIOClient; 19 | 20 | public interface ConnectListener { 21 | 22 | void onConnect(SocketIOClient client); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/DisconnectListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import com.corundumstudio.socketio.SocketIOClient; 19 | 20 | public interface DisconnectListener { 21 | 22 | void onDisconnect(SocketIOClient client); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/Store.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | 19 | public interface Store { 20 | 21 | void set(String key, Object val); 22 | 23 | T get(String key); 24 | 25 | boolean has(String key); 26 | 27 | void del(String key); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/PubSubType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | public enum PubSubType { 19 | 20 | CONNECT, DISCONNECT, JOIN, LEAVE, DISPATCH; 21 | 22 | @Override 23 | public String toString() { 24 | return name().toLowerCase(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/XHRPostMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import java.util.UUID; 19 | 20 | public class XHRPostMessage extends HttpMessage { 21 | 22 | public XHRPostMessage(String origin, UUID sessionId) { 23 | super(origin, sessionId); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/MultiTypeEventListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import com.corundumstudio.socketio.MultiTypeArgs; 19 | 20 | /** 21 | * Multi type args event listener 22 | * 23 | */ 24 | public interface MultiTypeEventListener extends DataListener { 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/XHROptionsMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import java.util.UUID; 19 | 20 | public class XHROptionsMessage extends XHRPostMessage { 21 | 22 | public XHROptionsMessage(String origin, UUID sessionId) { 23 | super(origin, sessionId); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/transport/BaseTransport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.transport; 17 | 18 | import io.netty.channel.ChannelInboundHandlerAdapter; 19 | 20 | import com.corundumstudio.socketio.Disconnectable; 21 | 22 | @Deprecated 23 | public abstract class BaseTransport extends ChannelInboundHandlerAdapter implements Disconnectable { 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/AckArgs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import java.util.List; 19 | 20 | public class AckArgs { 21 | 22 | private List args; 23 | 24 | public AckArgs(List args) { 25 | super(); 26 | this.args = args; 27 | } 28 | 29 | public List getArgs() { 30 | return args; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/PubSubStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | 19 | public interface PubSubStore { 20 | 21 | void publish(PubSubType type, PubSubMessage msg); 22 | 23 | void subscribe(PubSubType type, PubSubListener listener, Class clazz); 24 | 25 | void unsubscribe(PubSubType type); 26 | 27 | void shutdown(); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/AuthorizationListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | public interface AuthorizationListener { 19 | 20 | /** 21 | * Checks is client with handshake data is authorized 22 | * 23 | * @param data - handshake data 24 | * @return - true if client is authorized of false otherwise 25 | */ 26 | boolean isAuthorized(HandshakeData data); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/SuccessAuthorizationListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import com.corundumstudio.socketio.AuthorizationListener; 19 | import com.corundumstudio.socketio.HandshakeData; 20 | 21 | public class SuccessAuthorizationListener implements AuthorizationListener { 22 | 23 | @Override 24 | public boolean isAuthorized(HandshakeData data) { 25 | return true; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/EncoderBaseTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import com.corundumstudio.socketio.Configuration; 19 | import com.corundumstudio.socketio.protocol.PacketEncoder; 20 | import com.corundumstudio.socketio.protocol.JacksonJsonSupport; 21 | 22 | public class EncoderBaseTest { 23 | 24 | final PacketEncoder encoder = new PacketEncoder(new Configuration(), new JacksonJsonSupport()); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/HttpErrorMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import java.util.Map; 19 | 20 | public class HttpErrorMessage extends HttpMessage { 21 | 22 | private final Map data; 23 | 24 | public HttpErrorMessage(Map data) { 25 | super(null, null); 26 | this.data = data; 27 | } 28 | 29 | public Map getData() { 30 | return data; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/PubSubMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import java.io.Serializable; 19 | 20 | public abstract class PubSubMessage implements Serializable { 21 | 22 | private static final long serialVersionUID = -8789343104393884987L; 23 | 24 | private Long nodeId; 25 | 26 | public Long getNodeId() { 27 | return nodeId; 28 | } 29 | 30 | public void setNodeId(Long nodeId) { 31 | this.nodeId = nodeId; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/DataListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import com.corundumstudio.socketio.AckRequest; 19 | import com.corundumstudio.socketio.SocketIOClient; 20 | 21 | public interface DataListener { 22 | 23 | /** 24 | * Invokes when data object received from client 25 | * 26 | * @param client - receiver 27 | * @param data - received object 28 | */ 29 | void onData(SocketIOClient client, T data, AckRequest ackSender) throws Exception; 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/AnnotationScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.Method; 20 | 21 | import com.corundumstudio.socketio.namespace.Namespace; 22 | 23 | public interface AnnotationScanner { 24 | 25 | Class getScanAnnotation(); 26 | 27 | void addListener(Namespace namespace, Object object, Method method, Annotation annotation); 28 | 29 | void validate(Method method, Class clazz); 30 | 31 | } -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnConnect.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | 24 | /** 25 | * Annotation that defines Connect handler. 26 | * 27 | * Arguments in method: 28 | * 29 | * - SocketIOClient (required) 30 | * 31 | */ 32 | @Target(ElementType.METHOD) 33 | @Retention(RetentionPolicy.RUNTIME) 34 | public @interface OnConnect { 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/SocketIOException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | public class SocketIOException extends RuntimeException { 19 | 20 | private static final long serialVersionUID = -9218908839842557188L; 21 | 22 | public SocketIOException(String message, Throwable cause) { 23 | super(message, cause); 24 | } 25 | 26 | public SocketIOException(String message) { 27 | super(message); 28 | } 29 | 30 | public SocketIOException(Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnDisconnect.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation that defines Disconnect handler. 25 | * 26 | * Arguments in method: 27 | * 28 | * - SocketIOClient (required) 29 | * 30 | */ 31 | @Target(ElementType.METHOD) 32 | @Retention(RetentionPolicy.RUNTIME) 33 | public @interface OnDisconnect { 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/HttpMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import java.util.UUID; 19 | 20 | public abstract class HttpMessage { 21 | 22 | private final String origin; 23 | private final UUID sessionId; 24 | 25 | public HttpMessage(String origin, UUID sessionId) { 26 | this.origin = origin; 27 | this.sessionId = sessionId; 28 | } 29 | 30 | public String getOrigin() { 31 | return origin; 32 | } 33 | 34 | public UUID getSessionId() { 35 | return sessionId; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/Event.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import java.util.List; 19 | 20 | class Event { 21 | 22 | private String name; 23 | private List args; 24 | 25 | public Event() { 26 | } 27 | 28 | public Event(String name, List args) { 29 | super(); 30 | this.name = name; 31 | this.args = args; 32 | } 33 | 34 | public List getArgs() { 35 | return args; 36 | } 37 | 38 | public String getName() { 39 | return name; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/ConnectMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import java.util.UUID; 19 | 20 | public class ConnectMessage extends PubSubMessage { 21 | 22 | private static final long serialVersionUID = 3108918714495865101L; 23 | 24 | private UUID sessionId; 25 | 26 | public ConnectMessage() { 27 | } 28 | 29 | public ConnectMessage(UUID sessionId) { 30 | super(); 31 | this.sessionId = sessionId; 32 | } 33 | 34 | public UUID getSessionId() { 35 | return sessionId; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/MultiTypeAckCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | /** 19 | * Multi type ack callback used in case of multiple ack arguments 20 | * 21 | */ 22 | public abstract class MultiTypeAckCallback extends AckCallback { 23 | 24 | private Class[] resultClasses; 25 | 26 | public MultiTypeAckCallback(Class ... resultClasses) { 27 | super(MultiTypeArgs.class); 28 | this.resultClasses = resultClasses; 29 | } 30 | 31 | public Class[] getResultClasses() { 32 | return resultClasses; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/VoidAckCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | /** 19 | * Base ack callback with {@link Void} class as type. 20 | * 21 | */ 22 | public abstract class VoidAckCallback extends AckCallback { 23 | 24 | public VoidAckCallback() { 25 | super(Void.class); 26 | } 27 | 28 | public VoidAckCallback(int timeout) { 29 | super(Void.class, timeout); 30 | } 31 | 32 | @Override 33 | public final void onSuccess(Void result) { 34 | onSuccess(); 35 | } 36 | 37 | protected abstract void onSuccess(); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/DisconnectMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import java.util.UUID; 19 | 20 | public class DisconnectMessage extends PubSubMessage { 21 | 22 | private static final long serialVersionUID = -2763553673397520368L; 23 | 24 | private UUID sessionId; 25 | 26 | public DisconnectMessage() { 27 | } 28 | 29 | public DisconnectMessage(UUID sessionId) { 30 | super(); 31 | this.sessionId = sessionId; 32 | } 33 | 34 | public UUID getSessionId() { 35 | return sessionId; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/AckMode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | public enum AckMode { 19 | 20 | /** 21 | * Send ack-response automatically on each ack-request 22 | * skip exceptions during packet handling 23 | */ 24 | AUTO, 25 | 26 | /** 27 | * Send ack-response automatically on each ack-request 28 | * only after success packet handling 29 | */ 30 | AUTO_SUCCESS_ONLY, 31 | 32 | /** 33 | * Turn off auto ack-response sending. 34 | * Use AckRequest.sendAckData to send ack-response each time. 35 | * 36 | */ 37 | MANUAL 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/ExceptionListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | 20 | import java.util.List; 21 | 22 | import com.corundumstudio.socketio.SocketIOClient; 23 | 24 | public interface ExceptionListener { 25 | 26 | void onEventException(Exception e, List args, SocketIOClient client); 27 | 28 | void onDisconnectException(Exception e, SocketIOClient client); 29 | 30 | void onConnectException(Exception e, SocketIOClient client); 31 | 32 | boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderBaseTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import mockit.Mocked; 19 | 20 | import org.junit.Before; 21 | 22 | import com.corundumstudio.socketio.ack.AckManager; 23 | import com.corundumstudio.socketio.protocol.JacksonJsonSupport; 24 | import com.corundumstudio.socketio.protocol.PacketDecoder; 25 | 26 | 27 | public class DecoderBaseTest { 28 | 29 | @Mocked 30 | protected AckManager ackManager; 31 | 32 | protected PacketDecoder decoder; 33 | 34 | @Before 35 | public void before() { 36 | decoder = new PacketDecoder(new JacksonJsonSupport(), ackManager); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/scheduler/CancelableScheduler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.scheduler; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | 20 | import java.util.concurrent.TimeUnit; 21 | 22 | public interface CancelableScheduler { 23 | 24 | void update(ChannelHandlerContext ctx); 25 | 26 | void cancel(SchedulerKey key); 27 | 28 | void scheduleCallback(SchedulerKey key, Runnable runnable, long delay, TimeUnit unit); 29 | 30 | void schedule(Runnable runnable, long delay, TimeUnit unit); 31 | 32 | void schedule(SchedulerKey key, Runnable runnable, long delay, TimeUnit unit); 33 | 34 | void shutdown(); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/namespace/EventEntry.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.namespace; 17 | 18 | import java.util.Queue; 19 | import java.util.concurrent.ConcurrentLinkedQueue; 20 | 21 | import com.corundumstudio.socketio.listener.DataListener; 22 | 23 | public class EventEntry { 24 | 25 | private final Queue> listeners = new ConcurrentLinkedQueue>();; 26 | 27 | public EventEntry() { 28 | super(); 29 | } 30 | 31 | public void addListener(DataListener listener) { 32 | listeners.add(listener); 33 | } 34 | 35 | public Queue> getListeners() { 36 | return listeners; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/ClientListeners.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | public interface ClientListeners { 19 | 20 | void addMultiTypeEventListener(String eventName, MultiTypeEventListener listener, Class ... eventClass); 21 | 22 | void addEventListener(String eventName, Class eventClass, DataListener listener); 23 | 24 | void addDisconnectListener(DisconnectListener listener); 25 | 26 | void addConnectListener(ConnectListener listener); 27 | 28 | void addListeners(Object listeners); 29 | 30 | void addListeners(Object listeners, Class listenersClass); 31 | 32 | void removeAllListeners(String eventName); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnEvent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * Annotation that defines Event handler. 25 | * The value is required, and represents event name. 26 | * 27 | * Arguments in method: 28 | * 29 | * - SocketIOClient (optional) 30 | * - AckRequest (optional) 31 | * - Event data (optional) 32 | * 33 | */ 34 | @Target(ElementType.METHOD) 35 | @Retention(RetentionPolicy.RUNTIME) 36 | public @interface OnEvent { 37 | 38 | /** 39 | * Event name 40 | */ 41 | String value(); 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/MemoryStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import io.netty.util.internal.PlatformDependent; 19 | 20 | import java.util.Map; 21 | 22 | public class MemoryStore implements Store { 23 | 24 | private final Map store = PlatformDependent.newConcurrentHashMap(); 25 | 26 | @Override 27 | public void set(String key, Object value) { 28 | store.put(key, value); 29 | } 30 | 31 | @Override 32 | public T get(String key) { 33 | return (T) store.get(key); 34 | } 35 | 36 | @Override 37 | public boolean has(String key) { 38 | return store.containsKey(key); 39 | } 40 | 41 | @Override 42 | public void del(String key) { 43 | store.remove(key); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/ClientOperations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import com.corundumstudio.socketio.protocol.Packet; 19 | 20 | /** 21 | * Available client operations 22 | * 23 | */ 24 | public interface ClientOperations { 25 | 26 | /** 27 | * Send custom packet. 28 | * But {@link ClientOperations#sendEvent} method 29 | * usage is enough for most cases. 30 | * 31 | * @param packet - packet to send 32 | */ 33 | void send(Packet packet); 34 | 35 | /** 36 | * Disconnect client 37 | * 38 | */ 39 | void disconnect(); 40 | 41 | /** 42 | * Send event 43 | * 44 | * @param name - event name 45 | * @param data - event data 46 | */ 47 | void sendEvent(String name, Object ... data); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/OutPacketMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import com.corundumstudio.socketio.Transport; 19 | import com.corundumstudio.socketio.handler.ClientHead; 20 | 21 | public class OutPacketMessage extends HttpMessage { 22 | 23 | private final ClientHead clientHead; 24 | private final Transport transport; 25 | 26 | public OutPacketMessage(ClientHead clientHead, Transport transport) { 27 | super(clientHead.getOrigin(), clientHead.getSessionId()); 28 | 29 | this.clientHead = clientHead; 30 | this.transport = transport; 31 | } 32 | 33 | public Transport getTransport() { 34 | return transport; 35 | } 36 | 37 | public ClientHead getClientHead() { 38 | return clientHead; 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/MemoryPubSubStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import com.corundumstudio.socketio.store.pubsub.PubSubListener; 19 | import com.corundumstudio.socketio.store.pubsub.PubSubMessage; 20 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 21 | import com.corundumstudio.socketio.store.pubsub.PubSubType; 22 | 23 | public class MemoryPubSubStore implements PubSubStore { 24 | 25 | @Override 26 | public void publish(PubSubType type, PubSubMessage msg) { 27 | } 28 | 29 | @Override 30 | public void subscribe(PubSubType type, PubSubListener listener, Class clazz) { 31 | } 32 | 33 | @Override 34 | public void unsubscribe(PubSubType type) { 35 | } 36 | 37 | @Override 38 | public void shutdown() { 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/SocketIONamespace.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.Collection; 19 | import java.util.UUID; 20 | 21 | import com.corundumstudio.socketio.listener.ClientListeners; 22 | 23 | /** 24 | * Fully thread-safe. 25 | * 26 | */ 27 | public interface SocketIONamespace extends ClientListeners { 28 | 29 | String getName(); 30 | 31 | BroadcastOperations getBroadcastOperations(); 32 | 33 | BroadcastOperations getRoomOperations(String room); 34 | 35 | /** 36 | * Get all clients connected to namespace 37 | * 38 | * @return 39 | */ 40 | Collection getAllClients(); 41 | 42 | /** 43 | * Get client by uuid connected to namespace 44 | * 45 | * @param uuid 46 | * @return 47 | */ 48 | SocketIOClient getClient(UUID uuid); 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/Transport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import com.corundumstudio.socketio.transport.WebSocketTransport; 19 | import com.corundumstudio.socketio.transport.PollingTransport; 20 | 21 | public enum Transport { 22 | 23 | WEBSOCKET(WebSocketTransport.NAME), 24 | POLLING(PollingTransport.NAME); 25 | 26 | private final String value; 27 | 28 | Transport(String value) { 29 | this.value = value; 30 | } 31 | 32 | public String getValue() { 33 | return value; 34 | } 35 | 36 | public static Transport byName(String value) { 37 | for (Transport t : Transport.values()) { 38 | if (t.getValue().equals(value)) { 39 | return t; 40 | } 41 | } 42 | throw new IllegalArgumentException("Can't find " + value + " transport"); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/messages/PacketsMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.messages; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | 20 | import com.corundumstudio.socketio.Transport; 21 | import com.corundumstudio.socketio.handler.ClientHead; 22 | 23 | public class PacketsMessage { 24 | 25 | private final ClientHead client; 26 | private final ByteBuf content; 27 | private final Transport transport; 28 | 29 | public PacketsMessage(ClientHead client, ByteBuf content, Transport transport) { 30 | this.client = client; 31 | this.content = content; 32 | this.transport = transport; 33 | } 34 | 35 | public Transport getTransport() { 36 | return transport; 37 | } 38 | 39 | public ClientHead getClient() { 40 | return client; 41 | } 42 | 43 | public ByteBuf getContent() { 44 | return content; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/StoreFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.Map; 19 | import java.util.UUID; 20 | 21 | import com.corundumstudio.socketio.Disconnectable; 22 | import com.corundumstudio.socketio.handler.AuthorizeHandler; 23 | import com.corundumstudio.socketio.namespace.NamespacesHub; 24 | import com.corundumstudio.socketio.protocol.JsonSupport; 25 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 26 | 27 | /** 28 | * 29 | * Creates a client Store and PubSubStore 30 | * 31 | */ 32 | public interface StoreFactory extends Disconnectable { 33 | 34 | PubSubStore pubSubStore(); 35 | 36 | Map createMap(String name); 37 | 38 | Store createStore(UUID sessionId); 39 | 40 | void init(NamespacesHub namespacesHub, AuthorizeHandler authorizeHandler, JsonSupport jsonSupport); 41 | 42 | void shutdown(); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/JoinLeaveMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import java.util.UUID; 19 | 20 | public class JoinLeaveMessage extends PubSubMessage { 21 | 22 | private static final long serialVersionUID = -944515928988033174L; 23 | 24 | private UUID sessionId; 25 | private String namespace; 26 | private String room; 27 | 28 | public JoinLeaveMessage() { 29 | } 30 | 31 | public JoinLeaveMessage(UUID id, String room, String namespace) { 32 | super(); 33 | this.sessionId = id; 34 | this.room = room; 35 | this.namespace = namespace; 36 | } 37 | 38 | public String getNamespace() { 39 | return namespace; 40 | } 41 | 42 | public UUID getSessionId() { 43 | return sessionId; 44 | } 45 | 46 | public String getRoom() { 47 | return room; 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/DispatchMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import com.corundumstudio.socketio.protocol.Packet; 19 | 20 | public class DispatchMessage extends PubSubMessage { 21 | 22 | private static final long serialVersionUID = 6692047718303934349L; 23 | 24 | private String room; 25 | private String namespace; 26 | private Packet packet; 27 | 28 | public DispatchMessage() { 29 | } 30 | 31 | public DispatchMessage(String room, Packet packet, String namespace) { 32 | this.room = room; 33 | this.packet = packet; 34 | this.namespace = namespace; 35 | } 36 | 37 | public String getNamespace() { 38 | return namespace; 39 | } 40 | 41 | public Packet getPacket() { 42 | return packet; 43 | } 44 | 45 | public String getRoom() { 46 | return room; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/RedissonStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.Map; 19 | import java.util.UUID; 20 | 21 | import org.redisson.api.RedissonClient; 22 | 23 | public class RedissonStore implements Store { 24 | 25 | private final Map map; 26 | 27 | public RedissonStore(UUID sessionId, RedissonClient redisson) { 28 | this.map = redisson.getMap(sessionId.toString()); 29 | } 30 | 31 | @Override 32 | public void set(String key, Object value) { 33 | map.put(key, value); 34 | } 35 | 36 | @Override 37 | public T get(String key) { 38 | return (T) map.get(key); 39 | } 40 | 41 | @Override 42 | public boolean has(String key) { 43 | return map.containsKey(key); 44 | } 45 | 46 | @Override 47 | public void del(String key) { 48 | map.remove(key); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/ExceptionListenerAdapter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | 20 | import java.util.List; 21 | 22 | import com.corundumstudio.socketio.SocketIOClient; 23 | 24 | /** 25 | * Base callback exceptions listener 26 | * 27 | * 28 | */ 29 | public abstract class ExceptionListenerAdapter implements ExceptionListener { 30 | 31 | @Override 32 | public void onEventException(Exception e, List data, SocketIOClient client) { 33 | } 34 | 35 | @Override 36 | public void onDisconnectException(Exception e, SocketIOClient client) { 37 | } 38 | 39 | @Override 40 | public void onConnectException(Exception e, SocketIOClient client) { 41 | } 42 | 43 | @Override 44 | public boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { 45 | return false; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/TransportState.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import java.util.Queue; 19 | import java.util.concurrent.ConcurrentLinkedQueue; 20 | 21 | import com.corundumstudio.socketio.protocol.Packet; 22 | 23 | import io.netty.channel.Channel; 24 | 25 | public class TransportState { 26 | 27 | private Queue packetsQueue = new ConcurrentLinkedQueue(); 28 | private Channel channel; 29 | 30 | public void setPacketsQueue(Queue packetsQueue) { 31 | this.packetsQueue = packetsQueue; 32 | } 33 | 34 | public Queue getPacketsQueue() { 35 | return packetsQueue; 36 | } 37 | 38 | public Channel getChannel() { 39 | return channel; 40 | } 41 | 42 | public Channel update(Channel channel) { 43 | Channel prevChannel = this.channel; 44 | this.channel = channel; 45 | return prevChannel; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/HazelcastStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.UUID; 19 | 20 | import com.hazelcast.core.HazelcastInstance; 21 | import com.hazelcast.core.IMap; 22 | 23 | 24 | public class HazelcastStore implements Store { 25 | 26 | private final IMap map; 27 | 28 | public HazelcastStore(UUID sessionId, HazelcastInstance hazelcastInstance) { 29 | map = hazelcastInstance.getMap(sessionId.toString()); 30 | } 31 | 32 | @Override 33 | public void set(String key, Object val) { 34 | map.put(key, val); 35 | } 36 | 37 | @Override 38 | public T get(String key) { 39 | return (T) map.get(key); 40 | } 41 | 42 | @Override 43 | public boolean has(String key) { 44 | return map.containsKey(key); 45 | } 46 | 47 | @Override 48 | public void del(String key) { 49 | map.delete(key); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/AuthPacket.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import java.util.UUID; 19 | 20 | 21 | public class AuthPacket { 22 | 23 | private final UUID sid; 24 | private final String[] upgrades; 25 | private final int pingInterval; 26 | private final int pingTimeout; 27 | 28 | public AuthPacket(UUID sid, String[] upgrades, int pingInterval, int pingTimeout) { 29 | super(); 30 | this.sid = sid; 31 | this.upgrades = upgrades; 32 | this.pingInterval = pingInterval; 33 | this.pingTimeout = pingTimeout; 34 | } 35 | 36 | public int getPingInterval() { 37 | return pingInterval; 38 | } 39 | 40 | public int getPingTimeout() { 41 | return pingTimeout; 42 | } 43 | 44 | public UUID getSid() { 45 | return sid; 46 | } 47 | 48 | public String[] getUpgrades() { 49 | return upgrades; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/misc/IterableCollection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.misc; 17 | 18 | import java.util.AbstractCollection; 19 | import java.util.Iterator; 20 | 21 | public class IterableCollection extends AbstractCollection { 22 | 23 | private final CompositeIterable iterable; 24 | 25 | public IterableCollection(Iterable iterable) { 26 | this(new CompositeIterable(iterable)); 27 | } 28 | 29 | public IterableCollection(CompositeIterable iterable) { 30 | this.iterable = iterable; 31 | } 32 | 33 | @Override 34 | public Iterator iterator() { 35 | return new CompositeIterable(iterable).iterator(); 36 | } 37 | 38 | @Override 39 | public int size() { 40 | Iterator iterator = new CompositeIterable(iterable).iterator(); 41 | int count = 0; 42 | while (iterator.hasNext()) { 43 | iterator.next(); 44 | count++; 45 | } 46 | return count; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/JsonSupport.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import io.netty.buffer.ByteBufInputStream; 19 | import io.netty.buffer.ByteBufOutputStream; 20 | 21 | import java.io.IOException; 22 | import java.util.List; 23 | 24 | import com.corundumstudio.socketio.AckCallback; 25 | 26 | /** 27 | * JSON infrastructure interface. 28 | * Allows to implement custom realizations 29 | * to JSON support operations. 30 | * 31 | */ 32 | public interface JsonSupport { 33 | 34 | AckArgs readAckArgs(ByteBufInputStream src, AckCallback callback) throws IOException; 35 | 36 | T readValue(String namespaceName, ByteBufInputStream src, Class valueType) throws IOException; 37 | 38 | void writeValue(ByteBufOutputStream out, Object value) throws IOException; 39 | 40 | void addEventMapping(String namespaceName, String eventName, Class ... eventClass); 41 | 42 | void removeEventMapping(String namespaceName, String eventName); 43 | 44 | List getArrays(); 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/JoinIteratorsTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Arrays; 20 | import java.util.List; 21 | 22 | import org.junit.Assert; 23 | import org.junit.Test; 24 | 25 | import com.corundumstudio.socketio.misc.CompositeIterable; 26 | 27 | public class JoinIteratorsTest { 28 | 29 | @Test 30 | public void testIterator() { 31 | List list1 = Arrays.asList(1, 2); 32 | List list2 = Arrays.asList(3, 4); 33 | CompositeIterable iterators = new CompositeIterable(list1, list2); 34 | 35 | // for nomemory test 36 | for (Integer integer : iterators) { 37 | } 38 | 39 | List mainList = new ArrayList(); 40 | for (Integer integer : iterators) { 41 | mainList.add(integer); 42 | } 43 | Assert.assertEquals(list1.size() + list2.size(), mainList.size()); 44 | mainList.removeAll(list1); 45 | mainList.removeAll(list2); 46 | Assert.assertTrue(mainList.isEmpty()); 47 | 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/MemoryStoreFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import io.netty.util.internal.PlatformDependent; 19 | 20 | import java.util.Map; 21 | import java.util.UUID; 22 | 23 | import com.corundumstudio.socketio.store.pubsub.BaseStoreFactory; 24 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 25 | 26 | public class MemoryStoreFactory extends BaseStoreFactory { 27 | 28 | private final MemoryPubSubStore pubSubMemoryStore = new MemoryPubSubStore(); 29 | 30 | @Override 31 | public Store createStore(UUID sessionId) { 32 | return new MemoryStore(); 33 | } 34 | 35 | @Override 36 | public PubSubStore pubSubStore() { 37 | return pubSubMemoryStore; 38 | } 39 | 40 | @Override 41 | public void shutdown() { 42 | } 43 | 44 | @Override 45 | public String toString() { 46 | return getClass().getSimpleName() + " (local session store only)"; 47 | } 48 | 49 | @Override 50 | public Map createMap(String name) { 51 | return PlatformDependent.newConcurrentHashMap(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/listener/DefaultExceptionListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.listener; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | 20 | import java.util.List; 21 | 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import com.corundumstudio.socketio.SocketIOClient; 26 | 27 | public class DefaultExceptionListener extends ExceptionListenerAdapter { 28 | 29 | private static final Logger log = LoggerFactory.getLogger(DefaultExceptionListener.class); 30 | 31 | @Override 32 | public void onEventException(Exception e, List args, SocketIOClient client) { 33 | log.error(e.getMessage(), e); 34 | } 35 | 36 | @Override 37 | public void onDisconnectException(Exception e, SocketIOClient client) { 38 | log.error(e.getMessage(), e); 39 | } 40 | 41 | @Override 42 | public void onConnectException(Exception e, SocketIOClient client) { 43 | log.error(e.getMessage(), e); 44 | } 45 | 46 | @Override 47 | public boolean exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { 48 | log.error(e.getMessage(), e); 49 | return true; 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/ack/AckSchedulerKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.ack; 17 | 18 | import java.util.UUID; 19 | 20 | import com.corundumstudio.socketio.scheduler.SchedulerKey; 21 | 22 | public class AckSchedulerKey extends SchedulerKey { 23 | 24 | private final long index; 25 | 26 | public AckSchedulerKey(Type type, UUID sessionId, long index) { 27 | super(type, sessionId); 28 | this.index = index; 29 | } 30 | 31 | public long getIndex() { 32 | return index; 33 | } 34 | 35 | @Override 36 | public int hashCode() { 37 | final int prime = 31; 38 | int result = super.hashCode(); 39 | result = prime * result + (int) (index ^ (index >>> 32)); 40 | return result; 41 | } 42 | 43 | @Override 44 | public boolean equals(Object obj) { 45 | if (this == obj) 46 | return true; 47 | if (!super.equals(obj)) 48 | return false; 49 | if (getClass() != obj.getClass()) 50 | return false; 51 | AckSchedulerKey other = (AckSchedulerKey) obj; 52 | if (index != other.index) 53 | return false; 54 | return true; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/MultiTypeArgs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.Iterator; 19 | import java.util.List; 20 | 21 | public class MultiTypeArgs implements Iterable { 22 | 23 | private final List args; 24 | 25 | public MultiTypeArgs(List args) { 26 | super(); 27 | this.args = args; 28 | } 29 | 30 | public boolean isEmpty() { 31 | return size() == 0; 32 | } 33 | 34 | public int size() { 35 | return args.size(); 36 | } 37 | 38 | public List getArgs() { 39 | return args; 40 | } 41 | 42 | public T first() { 43 | return get(0); 44 | } 45 | 46 | public T second() { 47 | return get(1); 48 | } 49 | 50 | /** 51 | * "index out of bounds"-safe method for getting elements 52 | * 53 | * @param index 54 | * @return 55 | */ 56 | public T get(int index) { 57 | if (size() <= index) { 58 | return null; 59 | } 60 | return (T) args.get(index); 61 | } 62 | 63 | @Override 64 | public Iterator iterator() { 65 | return args.iterator(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/EncoderAckPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | 22 | import java.io.IOException; 23 | 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | 27 | import com.corundumstudio.socketio.protocol.Packet; 28 | import com.corundumstudio.socketio.protocol.PacketType; 29 | 30 | public class EncoderAckPacketTest extends EncoderBaseTest { 31 | 32 | @Test 33 | public void testEncode() throws IOException { 34 | Packet packet = new Packet(PacketType.ACK); 35 | packet.setAckId(140L); 36 | ByteBuf result = Unpooled.buffer(); 37 | // encoder.encodePacket(packet, result); 38 | Assert.assertEquals("6:::140", result.toString(CharsetUtil.UTF_8)); 39 | } 40 | 41 | @Test 42 | public void testEncodeWithArgs() throws IOException { 43 | Packet packet = new Packet(PacketType.ACK); 44 | packet.setAckId(12L); 45 | // packet.setArgs(Arrays.asList("woot", "wa")); 46 | ByteBuf result = Unpooled.buffer(); 47 | // encoder.encodePacket(packet, result); 48 | Assert.assertEquals("6:::12+[\"woot\",\"wa\"]", result.toString(CharsetUtil.UTF_8)); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/EncoderMessagePacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | 22 | import java.io.IOException; 23 | 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | 27 | import com.corundumstudio.socketio.protocol.Packet; 28 | import com.corundumstudio.socketio.protocol.PacketType; 29 | 30 | public class EncoderMessagePacketTest extends EncoderBaseTest { 31 | 32 | @Test 33 | public void testEncode() throws IOException { 34 | Packet packet = new Packet(PacketType.MESSAGE); 35 | packet.setData("woot"); 36 | ByteBuf result = Unpooled.buffer(); 37 | // encoder.encodePacket(packet, result); 38 | Assert.assertEquals("3:::woot", result.toString(CharsetUtil.UTF_8)); 39 | } 40 | 41 | @Test 42 | public void testEncodeWithIdAndEndpoint() throws IOException { 43 | Packet packet = new Packet(PacketType.MESSAGE); 44 | // packet.setId(5L); 45 | // packet.setAck(true); 46 | packet.setNsp("/tobi"); 47 | ByteBuf result = Unpooled.buffer(); 48 | // encoder.encodePacket(packet, result); 49 | Assert.assertEquals("3:5:/tobi", result.toString(CharsetUtil.UTF_8)); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/PacketType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | 19 | public enum PacketType { 20 | 21 | OPEN(0), CLOSE(1), PING(2), PONG(3), MESSAGE(4), UPGRADE(5), NOOP(6), 22 | 23 | CONNECT(0, true), DISCONNECT(1, true), EVENT(2, true), ACK(3, true), ERROR(4, true), BINARY_EVENT(5, true); 24 | 25 | public static final PacketType[] VALUES = values(); 26 | private final int value; 27 | private final boolean inner; 28 | 29 | PacketType(int value) { 30 | this(value, false); 31 | } 32 | 33 | PacketType(int value, boolean inner) { 34 | this.value = value; 35 | this.inner = inner; 36 | } 37 | 38 | public int getValue() { 39 | return value; 40 | } 41 | 42 | public static PacketType valueOf(int value) { 43 | for (PacketType type : VALUES) { 44 | if (type.getValue() == value && !type.inner) { 45 | return type; 46 | } 47 | } 48 | throw new IllegalStateException(); 49 | } 50 | 51 | public static PacketType valueOfInner(int value) { 52 | for (PacketType type : VALUES) { 53 | if (type.getValue() == value && type.inner) { 54 | return type; 55 | } 56 | } 57 | throw new IllegalArgumentException("Can't parse " + value); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/scheduler/SchedulerKey.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.scheduler; 17 | 18 | 19 | public class SchedulerKey { 20 | 21 | public enum Type {PING_TIMEOUT, ACK_TIMEOUT, UPGRADE_TIMEOUT}; 22 | 23 | private final Type type; 24 | private final Object sessionId; 25 | 26 | public SchedulerKey(Type type, Object sessionId) { 27 | this.type = type; 28 | this.sessionId = sessionId; 29 | } 30 | 31 | @Override 32 | public int hashCode() { 33 | final int prime = 31; 34 | int result = 1; 35 | result = prime * result 36 | + ((sessionId == null) ? 0 : sessionId.hashCode()); 37 | result = prime * result + ((type == null) ? 0 : type.hashCode()); 38 | return result; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object obj) { 43 | if (this == obj) 44 | return true; 45 | if (obj == null) 46 | return false; 47 | if (getClass() != obj.getClass()) 48 | return false; 49 | SchedulerKey other = (SchedulerKey) obj; 50 | if (sessionId == null) { 51 | if (other.sessionId != null) 52 | return false; 53 | } else if (!sessionId.equals(other.sessionId)) 54 | return false; 55 | if (type != other.type) 56 | return false; 57 | return true; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderJsonPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import java.io.IOException; 19 | import java.util.Map; 20 | 21 | import org.junit.Assert; 22 | import org.junit.Test; 23 | 24 | import com.corundumstudio.socketio.protocol.Packet; 25 | 26 | public class DecoderJsonPacketTest extends DecoderBaseTest { 27 | 28 | @Test 29 | public void testUTF8Decode() throws IOException { 30 | Packet packet = decoder.decodePacket("4:::\"Привет\"", null); 31 | // Assert.assertEquals(PacketType.JSON, packet.getType()); 32 | Assert.assertEquals("Привет", packet.getData()); 33 | } 34 | 35 | @Test 36 | public void testDecode() throws IOException { 37 | Packet packet = decoder.decodePacket("4:::\"2\"", null); 38 | // Assert.assertEquals(PacketType.JSON, packet.getType()); 39 | Assert.assertEquals("2", packet.getData()); 40 | } 41 | 42 | @Test 43 | public void testDecodeWithMessageIdAndAckData() throws IOException { 44 | Packet packet = decoder.decodePacket("4:1+::{\"a\":\"b\"}", null); 45 | // Assert.assertEquals(PacketType.JSON, packet.getType()); 46 | // Assert.assertEquals(1, (long)packet.getId()); 47 | // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); 48 | 49 | Map obj = (Map) packet.getData(); 50 | Assert.assertEquals("b", obj.get("a")); 51 | Assert.assertEquals(1, obj.size()); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderMessagePacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import java.io.IOException; 19 | 20 | import org.junit.Assert; 21 | import org.junit.Test; 22 | 23 | import com.corundumstudio.socketio.protocol.Packet; 24 | import com.corundumstudio.socketio.protocol.PacketType; 25 | 26 | public class DecoderMessagePacketTest extends DecoderBaseTest { 27 | 28 | @Test 29 | public void testDecodeId() throws IOException { 30 | Packet packet = decoder.decodePacket("3:1::asdfasdf", null); 31 | Assert.assertEquals(PacketType.MESSAGE, packet.getType()); 32 | // Assert.assertEquals(1, (long)packet.getId()); 33 | // Assert.assertTrue(packet.getArgs().isEmpty()); 34 | // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); 35 | } 36 | 37 | @Test 38 | public void testDecode() throws IOException { 39 | Packet packet = decoder.decodePacket("3:::woot", null); 40 | Assert.assertEquals(PacketType.MESSAGE, packet.getType()); 41 | Assert.assertEquals("woot", packet.getData()); 42 | } 43 | 44 | @Test 45 | public void testDecodeWithIdAndEndpoint() throws IOException { 46 | Packet packet = decoder.decodePacket("3:5:/tobi", null); 47 | Assert.assertEquals(PacketType.MESSAGE, packet.getType()); 48 | // Assert.assertEquals(5, (long)packet.getId()); 49 | // Assert.assertEquals(true, packet.getAck()); 50 | Assert.assertEquals("/tobi", packet.getNsp()); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderConnectionPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import java.io.IOException; 19 | 20 | import org.junit.Assert; 21 | import org.junit.Test; 22 | 23 | import com.corundumstudio.socketio.protocol.Packet; 24 | import com.corundumstudio.socketio.protocol.PacketType; 25 | 26 | public class DecoderConnectionPacketTest extends DecoderBaseTest { 27 | 28 | @Test 29 | public void testDecodeHeartbeat() throws IOException { 30 | Packet packet = decoder.decodePacket("2:::", null); 31 | // Assert.assertEquals(PacketType.HEARTBEAT, packet.getType()); 32 | } 33 | 34 | @Test 35 | public void testDecode() throws IOException { 36 | Packet packet = decoder.decodePacket("1::/tobi", null); 37 | Assert.assertEquals(PacketType.CONNECT, packet.getType()); 38 | Assert.assertEquals("/tobi", packet.getNsp()); 39 | } 40 | 41 | @Test 42 | public void testDecodeWithQueryString() throws IOException { 43 | Packet packet = decoder.decodePacket("1::/test:?test=1", null); 44 | Assert.assertEquals(PacketType.CONNECT, packet.getType()); 45 | Assert.assertEquals("/test", packet.getNsp()); 46 | // Assert.assertEquals("?test=1", packet.getQs()); 47 | } 48 | 49 | @Test 50 | public void testDecodeDisconnection() throws IOException { 51 | Packet packet = decoder.decodePacket("0::/woot", null); 52 | Assert.assertEquals(PacketType.DISCONNECT, packet.getType()); 53 | Assert.assertEquals("/woot", packet.getNsp()); 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/ClientsBox.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import io.netty.channel.Channel; 19 | import io.netty.util.internal.PlatformDependent; 20 | 21 | import java.util.Map; 22 | import java.util.UUID; 23 | 24 | import com.corundumstudio.socketio.HandshakeData; 25 | 26 | public class ClientsBox { 27 | 28 | private final Map uuid2clients = PlatformDependent.newConcurrentHashMap(); 29 | private final Map channel2clients = PlatformDependent.newConcurrentHashMap(); 30 | 31 | // TODO use storeFactory 32 | public HandshakeData getHandshakeData(UUID sessionId) { 33 | ClientHead client = uuid2clients.get(sessionId); 34 | if (client == null) { 35 | return null; 36 | } 37 | 38 | return client.getHandshakeData(); 39 | } 40 | 41 | public void addClient(ClientHead clientHead) { 42 | uuid2clients.put(clientHead.getSessionId(), clientHead); 43 | } 44 | 45 | public void removeClient(UUID sessionId) { 46 | uuid2clients.remove(sessionId); 47 | } 48 | 49 | public ClientHead get(UUID sessionId) { 50 | return uuid2clients.get(sessionId); 51 | } 52 | 53 | public void add(Channel channel, ClientHead clientHead) { 54 | channel2clients.put(channel, clientHead); 55 | } 56 | 57 | public void remove(Channel channel) { 58 | channel2clients.remove(channel); 59 | } 60 | 61 | 62 | public ClientHead get(Channel channel) { 63 | return channel2clients.get(channel); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/WrongUrlHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; 19 | 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | import io.netty.channel.Channel; 24 | import io.netty.channel.ChannelFuture; 25 | import io.netty.channel.ChannelFutureListener; 26 | import io.netty.channel.ChannelHandler.Sharable; 27 | import io.netty.channel.ChannelHandlerContext; 28 | import io.netty.channel.ChannelInboundHandlerAdapter; 29 | import io.netty.handler.codec.http.DefaultHttpResponse; 30 | import io.netty.handler.codec.http.FullHttpRequest; 31 | import io.netty.handler.codec.http.HttpResponse; 32 | import io.netty.handler.codec.http.HttpResponseStatus; 33 | import io.netty.handler.codec.http.QueryStringDecoder; 34 | 35 | @Sharable 36 | public class WrongUrlHandler extends ChannelInboundHandlerAdapter { 37 | 38 | private static final Logger log = LoggerFactory.getLogger(WrongUrlHandler.class); 39 | 40 | @Override 41 | public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 42 | if (msg instanceof FullHttpRequest) { 43 | FullHttpRequest req = (FullHttpRequest) msg; 44 | Channel channel = ctx.channel(); 45 | QueryStringDecoder queryDecoder = new QueryStringDecoder(req.uri()); 46 | 47 | HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST); 48 | ChannelFuture f = channel.writeAndFlush(res); 49 | f.addListener(ChannelFutureListener.CLOSE); 50 | req.release(); 51 | log.warn("Blocked wrong socket.io-context request! url: {}, params: {}, ip: {}", queryDecoder.path(), queryDecoder.parameters(), channel.remoteAddress()); 52 | return; 53 | } 54 | super.channelRead(ctx, msg); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/EncoderEventPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | 22 | import java.io.IOException; 23 | 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | 27 | import com.corundumstudio.socketio.protocol.Packet; 28 | import com.corundumstudio.socketio.protocol.PacketType; 29 | 30 | public class EncoderEventPacketTest extends EncoderBaseTest { 31 | 32 | @Test 33 | public void testEncode() throws IOException { 34 | Packet packet = new Packet(PacketType.EVENT); 35 | packet.setName("woot"); 36 | ByteBuf result = Unpooled.buffer(); 37 | // encoder.encodePacket(packet, result); 38 | Assert.assertEquals("5:::{\"name\":\"woot\"}", result.toString(CharsetUtil.UTF_8)); 39 | } 40 | 41 | @Test 42 | public void testEncodeWithMessageIdAndAck() throws IOException { 43 | Packet packet = new Packet(PacketType.EVENT); 44 | // packet.setId(1L); 45 | // packet.setAck(Packet.ACK_DATA); 46 | packet.setName("tobi"); 47 | ByteBuf result = Unpooled.buffer(); 48 | // encoder.encodePacket(packet, result); 49 | Assert.assertEquals("5:1+::{\"name\":\"tobi\"}", result.toString(CharsetUtil.UTF_8)); 50 | } 51 | 52 | @Test 53 | public void testEncodeWithData() throws IOException { 54 | Packet packet = new Packet(PacketType.EVENT); 55 | packet.setName("edwald"); 56 | // packet.setArgs(Arrays.asList(Collections.singletonMap("a", "b"), 2, "3")); 57 | ByteBuf result = Unpooled.buffer(); 58 | // encoder.encodePacket(packet, result); 59 | Assert.assertEquals("5:::{\"name\":\"edwald\",\"args\":[{\"a\":\"b\"},2,\"3\"]}", 60 | result.toString(CharsetUtil.UTF_8)); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderAckPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import java.io.IOException; 19 | import java.util.UUID; 20 | 21 | import mockit.Expectations; 22 | 23 | import org.junit.Assert; 24 | import org.junit.Test; 25 | 26 | import com.corundumstudio.socketio.AckCallback; 27 | import com.corundumstudio.socketio.protocol.Packet; 28 | import com.corundumstudio.socketio.protocol.PacketType; 29 | import com.fasterxml.jackson.core.JsonParseException; 30 | 31 | public class DecoderAckPacketTest extends DecoderBaseTest { 32 | 33 | @Test 34 | public void testDecode() throws IOException { 35 | Packet packet = decoder.decodePacket("6:::140", null); 36 | Assert.assertEquals(PacketType.ACK, packet.getType()); 37 | Assert.assertEquals(140, (long)packet.getAckId()); 38 | // Assert.assertTrue(packet.getArgs().isEmpty()); 39 | } 40 | 41 | @Test 42 | public void testDecodeWithArgs() throws IOException { 43 | initExpectations(); 44 | 45 | Packet packet = decoder.decodePacket("6:::12+[\"woot\",\"wa\"]", null); 46 | Assert.assertEquals(PacketType.ACK, packet.getType()); 47 | Assert.assertEquals(12, (long)packet.getAckId()); 48 | // Assert.assertEquals(Arrays.asList("woot", "wa"), packet.getArgs()); 49 | } 50 | 51 | private void initExpectations() { 52 | new Expectations() {{ 53 | ackManager.getCallback((UUID)any, anyInt); 54 | result = new AckCallback(String.class) { 55 | @Override 56 | public void onSuccess(String result) { 57 | } 58 | }; 59 | }}; 60 | } 61 | 62 | @Test(expected = JsonParseException.class) 63 | public void testDecodeWithBadJson() throws IOException { 64 | initExpectations(); 65 | decoder.decodePacket("6:::1+{\"++]", null); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/RedissonStoreFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.Map; 19 | import java.util.UUID; 20 | 21 | import org.redisson.Redisson; 22 | import org.redisson.api.RedissonClient; 23 | 24 | import com.corundumstudio.socketio.store.pubsub.BaseStoreFactory; 25 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 26 | 27 | public class RedissonStoreFactory extends BaseStoreFactory { 28 | 29 | private final RedissonClient redisClient; 30 | private final RedissonClient redisPub; 31 | private final RedissonClient redisSub; 32 | 33 | private final PubSubStore pubSubStore; 34 | 35 | public RedissonStoreFactory() { 36 | this(Redisson.create()); 37 | } 38 | 39 | public RedissonStoreFactory(RedissonClient redisson) { 40 | this.redisClient = redisson; 41 | this.redisPub = redisson; 42 | this.redisSub = redisson; 43 | 44 | this.pubSubStore = new RedissonPubSubStore(redisPub, redisSub, getNodeId()); 45 | } 46 | 47 | public RedissonStoreFactory(Redisson redisClient, Redisson redisPub, Redisson redisSub) { 48 | this.redisClient = redisClient; 49 | this.redisPub = redisPub; 50 | this.redisSub = redisSub; 51 | 52 | this.pubSubStore = new RedissonPubSubStore(redisPub, redisSub, getNodeId()); 53 | } 54 | 55 | @Override 56 | public Store createStore(UUID sessionId) { 57 | return new RedissonStore(sessionId, redisClient); 58 | } 59 | 60 | @Override 61 | public PubSubStore pubSubStore() { 62 | return pubSubStore; 63 | } 64 | 65 | @Override 66 | public void shutdown() { 67 | redisClient.shutdown(); 68 | redisPub.shutdown(); 69 | redisSub.shutdown(); 70 | } 71 | 72 | @Override 73 | public Map createMap(String name) { 74 | return redisClient.getMap(name); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/BroadcastAckCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.concurrent.atomic.AtomicBoolean; 19 | import java.util.concurrent.atomic.AtomicInteger; 20 | 21 | public class BroadcastAckCallback { 22 | 23 | final AtomicBoolean loopFinished = new AtomicBoolean(); 24 | final AtomicInteger counter = new AtomicInteger(); 25 | final AtomicBoolean successExecuted = new AtomicBoolean(); 26 | final Class resultClass; 27 | final int timeout; 28 | 29 | public BroadcastAckCallback(Class resultClass, int timeout) { 30 | this.resultClass = resultClass; 31 | this.timeout = timeout; 32 | } 33 | 34 | public BroadcastAckCallback(Class resultClass) { 35 | this(resultClass, -1); 36 | } 37 | 38 | final AckCallback createClientCallback(final SocketIOClient client) { 39 | counter.getAndIncrement(); 40 | return new AckCallback(resultClass, timeout) { 41 | @Override 42 | public void onSuccess(T result) { 43 | counter.getAndDecrement(); 44 | onClientSuccess(client, result); 45 | executeSuccess(); 46 | } 47 | 48 | @Override 49 | public void onTimeout() { 50 | onClientTimeout(client); 51 | } 52 | 53 | }; 54 | } 55 | 56 | protected void onClientTimeout(SocketIOClient client) { 57 | 58 | } 59 | 60 | protected void onClientSuccess(SocketIOClient client, T result) { 61 | 62 | } 63 | 64 | protected void onAllSuccess() { 65 | 66 | } 67 | 68 | private void executeSuccess() { 69 | if (loopFinished.get() 70 | && counter.get() == 0 71 | && successExecuted.compareAndSet(false, true)) { 72 | onAllSuccess(); 73 | } 74 | } 75 | 76 | void loopFinished() { 77 | loopFinished.set(true); 78 | executeSuccess(); 79 | } 80 | 81 | } 82 | 83 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/EncoderConnectionPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | 22 | import java.io.IOException; 23 | 24 | import org.junit.Assert; 25 | import org.junit.Test; 26 | 27 | import com.corundumstudio.socketio.protocol.Packet; 28 | import com.corundumstudio.socketio.protocol.PacketType; 29 | 30 | public class EncoderConnectionPacketTest extends EncoderBaseTest { 31 | 32 | @Test 33 | public void testEncodeHeartbeat() throws IOException { 34 | // Packet packet = new Packet(PacketType.HEARTBEAT); 35 | // ByteBuf result = Unpooled.buffer(); 36 | // encoder.encodePacket(packet, result); 37 | // Assert.assertEquals("2::", result.toString(CharsetUtil.UTF_8)); 38 | } 39 | 40 | @Test 41 | public void testEncodeDisconnection() throws IOException { 42 | Packet packet = new Packet(PacketType.DISCONNECT); 43 | packet.setNsp("/woot"); 44 | ByteBuf result = Unpooled.buffer(); 45 | // encoder.encodePacket(packet, result); 46 | Assert.assertEquals("0::/woot", result.toString(CharsetUtil.UTF_8)); 47 | } 48 | 49 | @Test 50 | public void testEncode() throws IOException { 51 | Packet packet = new Packet(PacketType.CONNECT); 52 | packet.setNsp("/tobi"); 53 | ByteBuf result = Unpooled.buffer(); 54 | // encoder.encodePacket(packet, result); 55 | Assert.assertEquals("1::/tobi", result.toString(CharsetUtil.UTF_8)); 56 | } 57 | 58 | @Test 59 | public void testEncodePacketWithQueryString() throws IOException { 60 | Packet packet = new Packet(PacketType.CONNECT); 61 | packet.setNsp("/test"); 62 | // packet.setQs("?test=1"); 63 | ByteBuf result = Unpooled.buffer(); 64 | // encoder.encodePacket(packet, result); 65 | Assert.assertEquals("1::/test:?test=1", result.toString(CharsetUtil.UTF_8)); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnConnectScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.InvocationTargetException; 20 | import java.lang.reflect.Method; 21 | 22 | import com.corundumstudio.socketio.SocketIOClient; 23 | import com.corundumstudio.socketio.handler.SocketIOException; 24 | import com.corundumstudio.socketio.listener.ConnectListener; 25 | import com.corundumstudio.socketio.namespace.Namespace; 26 | 27 | public class OnConnectScanner implements AnnotationScanner { 28 | 29 | @Override 30 | public Class getScanAnnotation() { 31 | return OnConnect.class; 32 | } 33 | 34 | @Override 35 | public void addListener(Namespace namespace, final Object object, final Method method, Annotation annotation) { 36 | namespace.addConnectListener(new ConnectListener() { 37 | @Override 38 | public void onConnect(SocketIOClient client) { 39 | try { 40 | method.invoke(object, client); 41 | } catch (InvocationTargetException e) { 42 | throw new SocketIOException(e.getCause()); 43 | } catch (Exception e) { 44 | throw new SocketIOException(e); 45 | } 46 | } 47 | }); 48 | } 49 | 50 | @Override 51 | public void validate(Method method, Class clazz) { 52 | if (method.getParameterTypes().length != 1) { 53 | throw new IllegalArgumentException("Wrong OnConnect listener signature: " + clazz + "." + method.getName()); 54 | } 55 | boolean valid = false; 56 | for (Class eventType : method.getParameterTypes()) { 57 | if (eventType.equals(SocketIOClient.class)) { 58 | valid = true; 59 | } 60 | } 61 | if (!valid) { 62 | throw new IllegalArgumentException("Wrong OnConnect listener signature: " + clazz + "." + method.getName()); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnDisconnectScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.InvocationTargetException; 20 | import java.lang.reflect.Method; 21 | 22 | import com.corundumstudio.socketio.SocketIOClient; 23 | import com.corundumstudio.socketio.handler.SocketIOException; 24 | import com.corundumstudio.socketio.listener.DisconnectListener; 25 | import com.corundumstudio.socketio.namespace.Namespace; 26 | 27 | public class OnDisconnectScanner implements AnnotationScanner { 28 | 29 | @Override 30 | public Class getScanAnnotation() { 31 | return OnDisconnect.class; 32 | } 33 | 34 | @Override 35 | public void addListener(Namespace namespace, final Object object, final Method method, Annotation annotation) { 36 | namespace.addDisconnectListener(new DisconnectListener() { 37 | @Override 38 | public void onDisconnect(SocketIOClient client) { 39 | try { 40 | method.invoke(object, client); 41 | } catch (InvocationTargetException e) { 42 | throw new SocketIOException(e.getCause()); 43 | } catch (Exception e) { 44 | throw new SocketIOException(e); 45 | } 46 | } 47 | }); 48 | } 49 | 50 | @Override 51 | public void validate(Method method, Class clazz) { 52 | if (method.getParameterTypes().length != 1) { 53 | throw new IllegalArgumentException("Wrong OnDisconnect listener signature: " + clazz + "." + method.getName()); 54 | } 55 | boolean valid = false; 56 | for (Class eventType : method.getParameterTypes()) { 57 | if (eventType.equals(SocketIOClient.class)) { 58 | valid = true; 59 | } 60 | } 61 | if (!valid) { 62 | throw new IllegalArgumentException("Wrong OnDisconnect listener signature: " + clazz + "." + method.getName()); 63 | } 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/AckCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | 19 | /** 20 | * Base ack callback class. 21 | * 22 | * Notifies about acknowledgement received from client 23 | * via {@link #onSuccess} callback method. 24 | * 25 | * By default it may wait acknowledgement from client 26 | * while {@link SocketIOClient} is alive. Timeout can be 27 | * defined {@link #timeout} as constructor argument. 28 | * 29 | * This object is NOT actual anymore if {@link #onSuccess} or 30 | * {@link #onTimeout} was executed. 31 | * 32 | * @param - any serializable type 33 | * 34 | * @see com.corundumstudio.socketio.VoidAckCallback 35 | * @see com.corundumstudio.socketio.MultiTypeAckCallback 36 | * 37 | */ 38 | public abstract class AckCallback { 39 | 40 | protected final Class resultClass; 41 | protected final int timeout; 42 | 43 | /** 44 | * Create AckCallback 45 | * 46 | * @param resultClass - result class 47 | */ 48 | public AckCallback(Class resultClass) { 49 | this(resultClass, -1); 50 | } 51 | 52 | /** 53 | * Creates AckCallback with timeout 54 | * 55 | * @param resultClass - result class 56 | * @param timeout - callback timeout in seconds 57 | */ 58 | public AckCallback(Class resultClass, int timeout) { 59 | this.resultClass = resultClass; 60 | this.timeout = timeout; 61 | } 62 | 63 | public int getTimeout() { 64 | return timeout; 65 | } 66 | 67 | /** 68 | * Executes only once when acknowledgement received from client. 69 | * 70 | * @param result - object sended by client 71 | */ 72 | public abstract void onSuccess(T result); 73 | 74 | /** 75 | * Invoked only once then timeout defined 76 | * 77 | */ 78 | public void onTimeout() { 79 | 80 | } 81 | 82 | /** 83 | * Returns class of argument in {@link #onSuccess} method 84 | * 85 | * @return - result class 86 | */ 87 | public Class getResultClass() { 88 | return resultClass; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/SocketConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | /** 19 | * TCP socket configuration contains configuration for main server channel 20 | * and client channels 21 | * 22 | * @see java.net.SocketOptions 23 | */ 24 | public class SocketConfig { 25 | 26 | private boolean tcpNoDelay = true; 27 | 28 | private int tcpSendBufferSize = -1; 29 | 30 | private int tcpReceiveBufferSize = -1; 31 | 32 | private boolean tcpKeepAlive = false; 33 | 34 | private int soLinger = -1; 35 | 36 | private boolean reuseAddress = false; 37 | 38 | private int acceptBackLog = 1024; 39 | 40 | public boolean isTcpNoDelay() { 41 | return tcpNoDelay; 42 | } 43 | public void setTcpNoDelay(boolean tcpNoDelay) { 44 | this.tcpNoDelay = tcpNoDelay; 45 | } 46 | 47 | public int getTcpSendBufferSize() { 48 | return tcpSendBufferSize; 49 | } 50 | public void setTcpSendBufferSize(int tcpSendBufferSize) { 51 | this.tcpSendBufferSize = tcpSendBufferSize; 52 | } 53 | 54 | public int getTcpReceiveBufferSize() { 55 | return tcpReceiveBufferSize; 56 | } 57 | public void setTcpReceiveBufferSize(int tcpReceiveBufferSize) { 58 | this.tcpReceiveBufferSize = tcpReceiveBufferSize; 59 | } 60 | 61 | public boolean isTcpKeepAlive() { 62 | return tcpKeepAlive; 63 | } 64 | public void setTcpKeepAlive(boolean tcpKeepAlive) { 65 | this.tcpKeepAlive = tcpKeepAlive; 66 | } 67 | 68 | public int getSoLinger() { 69 | return soLinger; 70 | } 71 | public void setSoLinger(int soLinger) { 72 | this.soLinger = soLinger; 73 | } 74 | 75 | public boolean isReuseAddress() { 76 | return reuseAddress; 77 | } 78 | public void setReuseAddress(boolean reuseAddress) { 79 | this.reuseAddress = reuseAddress; 80 | } 81 | 82 | public int getAcceptBackLog() { 83 | return acceptBackLog; 84 | } 85 | public void setAcceptBackLog(int acceptBackLog) { 86 | this.acceptBackLog = acceptBackLog; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/DecoderEventPacketTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import java.io.IOException; 19 | import java.util.HashMap; 20 | 21 | import org.junit.Assert; 22 | import org.junit.Test; 23 | 24 | import com.corundumstudio.socketio.protocol.JacksonJsonSupport; 25 | import com.corundumstudio.socketio.protocol.Packet; 26 | import com.corundumstudio.socketio.protocol.PacketDecoder; 27 | import com.corundumstudio.socketio.protocol.PacketType; 28 | 29 | public class DecoderEventPacketTest extends DecoderBaseTest { 30 | 31 | @Test 32 | public void testDecode() throws IOException { 33 | Packet packet = decoder.decodePacket("5:::{\"name\":\"woot\"}", null); 34 | Assert.assertEquals(PacketType.EVENT, packet.getType()); 35 | Assert.assertEquals("woot", packet.getName()); 36 | } 37 | 38 | @Test 39 | public void testDecodeWithMessageIdAndAck() throws IOException { 40 | Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null); 41 | Assert.assertEquals(PacketType.EVENT, packet.getType()); 42 | // Assert.assertEquals(1, (long)packet.getId()); 43 | // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); 44 | Assert.assertEquals("tobi", packet.getName()); 45 | } 46 | 47 | @Test 48 | public void testDecodeWithData() throws IOException { 49 | JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); 50 | jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); 51 | PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); 52 | 53 | Packet packet = decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null); 54 | Assert.assertEquals(PacketType.EVENT, packet.getType()); 55 | Assert.assertEquals("edwald", packet.getName()); 56 | // Assert.assertEquals(3, packet.getArgs().size()); 57 | // Map obj = (Map) packet.getArgs().get(0); 58 | // Assert.assertEquals("b", obj.get("a")); 59 | // Assert.assertEquals(2, packet.getArgs().get(1)); 60 | // Assert.assertEquals("3", packet.getArgs().get(2)); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/HazelcastStoreFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.Map; 19 | import java.util.UUID; 20 | 21 | import com.corundumstudio.socketio.store.pubsub.BaseStoreFactory; 22 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 23 | import com.hazelcast.client.HazelcastClient; 24 | import com.hazelcast.core.HazelcastInstance; 25 | 26 | /** 27 | * WARN: It's necessary to add netty-socketio.jar in hazelcast server classpath. 28 | * 29 | */ 30 | public class HazelcastStoreFactory extends BaseStoreFactory { 31 | 32 | private final HazelcastInstance hazelcastClient; 33 | private final HazelcastInstance hazelcastPub; 34 | private final HazelcastInstance hazelcastSub; 35 | 36 | private final PubSubStore pubSubStore; 37 | 38 | public HazelcastStoreFactory() { 39 | this(HazelcastClient.newHazelcastClient()); 40 | } 41 | 42 | public HazelcastStoreFactory(HazelcastInstance instance) { 43 | this.hazelcastClient = instance; 44 | this.hazelcastPub = instance; 45 | this.hazelcastSub = instance; 46 | 47 | this.pubSubStore = new HazelcastPubSubStore(hazelcastPub, hazelcastSub, getNodeId()); 48 | } 49 | 50 | public HazelcastStoreFactory(HazelcastInstance hazelcastClient, HazelcastInstance hazelcastPub, HazelcastInstance hazelcastSub) { 51 | this.hazelcastClient = hazelcastClient; 52 | this.hazelcastPub = hazelcastPub; 53 | this.hazelcastSub = hazelcastSub; 54 | 55 | this.pubSubStore = new HazelcastPubSubStore(hazelcastPub, hazelcastSub, getNodeId()); 56 | } 57 | 58 | @Override 59 | public Store createStore(UUID sessionId) { 60 | return new HazelcastStore(sessionId, hazelcastClient); 61 | } 62 | 63 | @Override 64 | public void shutdown() { 65 | hazelcastClient.shutdown(); 66 | hazelcastPub.shutdown(); 67 | hazelcastSub.shutdown(); 68 | } 69 | 70 | @Override 71 | public PubSubStore pubSubStore() { 72 | return pubSubStore; 73 | } 74 | 75 | @Override 76 | public Map createMap(String name) { 77 | return hazelcastClient.getMap(name); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/misc/CompositeIterable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.misc; 17 | 18 | import java.util.ArrayList; 19 | import java.util.Iterator; 20 | import java.util.List; 21 | 22 | public class CompositeIterable implements Iterable, Iterator { 23 | 24 | private List> iterablesList; 25 | private Iterable[] iterables; 26 | 27 | private Iterator> listIterator; 28 | private Iterator currentIterator; 29 | 30 | public CompositeIterable(List> iterables) { 31 | this.iterablesList = iterables; 32 | } 33 | 34 | public CompositeIterable(Iterable ... iterables) { 35 | this.iterables = iterables; 36 | } 37 | 38 | public CompositeIterable(CompositeIterable iterable) { 39 | this.iterables = iterable.iterables; 40 | this.iterablesList = iterable.iterablesList; 41 | } 42 | 43 | @Override 44 | public Iterator iterator() { 45 | List> iterators = new ArrayList>(); 46 | if (iterables != null) { 47 | for (Iterable iterable : iterables) { 48 | iterators.add(iterable.iterator()); 49 | } 50 | } else { 51 | for (Iterable iterable : iterablesList) { 52 | iterators.add(iterable.iterator()); 53 | } 54 | } 55 | listIterator = iterators.iterator(); 56 | currentIterator = null; 57 | return this; 58 | } 59 | 60 | @Override 61 | public boolean hasNext() { 62 | if (currentIterator == null || !currentIterator.hasNext()) { 63 | while (listIterator.hasNext()) { 64 | Iterator iterator = listIterator.next(); 65 | if (iterator.hasNext()) { 66 | currentIterator = iterator; 67 | return true; 68 | } 69 | } 70 | return false; 71 | } 72 | return currentIterator.hasNext(); 73 | } 74 | 75 | @Override 76 | public T next() { 77 | hasNext(); 78 | return currentIterator.next(); 79 | } 80 | 81 | @Override 82 | public void remove() { 83 | currentIterator.remove(); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/namespace/NamespacesHub.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.namespace; 17 | 18 | import io.netty.util.internal.PlatformDependent; 19 | 20 | import java.util.ArrayList; 21 | import java.util.Collection; 22 | import java.util.List; 23 | import java.util.concurrent.ConcurrentMap; 24 | 25 | import com.corundumstudio.socketio.Configuration; 26 | import com.corundumstudio.socketio.SocketIOClient; 27 | import com.corundumstudio.socketio.SocketIONamespace; 28 | import com.corundumstudio.socketio.misc.CompositeIterable; 29 | 30 | public class NamespacesHub { 31 | 32 | private final ConcurrentMap namespaces = PlatformDependent.newConcurrentHashMap(); 33 | private final Configuration configuration; 34 | 35 | public NamespacesHub(Configuration configuration) { 36 | this.configuration = configuration; 37 | } 38 | 39 | public Namespace create(String name) { 40 | Namespace namespace = (Namespace) namespaces.get(name); 41 | if (namespace == null) { 42 | namespace = new Namespace(name, configuration); 43 | Namespace oldNamespace = (Namespace) namespaces.putIfAbsent(name, namespace); 44 | if (oldNamespace != null) { 45 | namespace = oldNamespace; 46 | } 47 | } 48 | return namespace; 49 | } 50 | 51 | public Iterable getRoomClients(String room) { 52 | List> allClients = new ArrayList>(); 53 | for (SocketIONamespace namespace : namespaces.values()) { 54 | Iterable clients = ((Namespace)namespace).getRoomClients(room); 55 | allClients.add(clients); 56 | } 57 | return new CompositeIterable(allClients); 58 | } 59 | 60 | public Namespace get(String name) { 61 | return (Namespace) namespaces.get(name); 62 | } 63 | 64 | public void remove(String name) { 65 | SocketIONamespace namespace = namespaces.remove(name); 66 | if (namespace != null) { 67 | namespace.getBroadcastOperations().disconnect(); 68 | } 69 | } 70 | 71 | public Collection getAllNamespaces() { 72 | return namespaces.values(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/SocketIOClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.net.SocketAddress; 19 | import java.util.Set; 20 | import java.util.UUID; 21 | 22 | import com.corundumstudio.socketio.protocol.Packet; 23 | import com.corundumstudio.socketio.store.Store; 24 | 25 | 26 | /** 27 | * Fully thread-safe. 28 | * 29 | */ 30 | public interface SocketIOClient extends ClientOperations, Store { 31 | 32 | /** 33 | * Handshake data used during client connection 34 | * 35 | * @return HandshakeData 36 | */ 37 | HandshakeData getHandshakeData(); 38 | 39 | /** 40 | * Current client transport protocol 41 | * 42 | * @return transport protocol 43 | */ 44 | Transport getTransport(); 45 | 46 | /** 47 | * Send event with ack callback 48 | * 49 | * @param name - event name 50 | * @param data - event data 51 | * @param ackCallback - ack callback 52 | */ 53 | void sendEvent(String name, AckCallback ackCallback, Object ... data); 54 | 55 | /** 56 | * Send packet with ack callback 57 | * 58 | * @param packet - packet to send 59 | * @param ackCallback - ack callback 60 | */ 61 | void send(Packet packet, AckCallback ackCallback); 62 | 63 | /** 64 | * Client namespace 65 | * 66 | * @return - namespace 67 | */ 68 | SocketIONamespace getNamespace(); 69 | 70 | /** 71 | * Client session id, uses {@link UUID} object 72 | * 73 | * @return - session id 74 | */ 75 | UUID getSessionId(); 76 | 77 | /** 78 | * Get client remote address 79 | * 80 | * @return remote address 81 | */ 82 | SocketAddress getRemoteAddress(); 83 | 84 | /** 85 | * Check is underlying channel open 86 | * 87 | * @return true if channel open, otherwise false 88 | */ 89 | boolean isChannelOpen(); 90 | 91 | /** 92 | * Join client to room 93 | * 94 | * @param room 95 | */ 96 | void joinRoom(String room); 97 | 98 | /** 99 | * Join client to room 100 | * 101 | * @param room 102 | */ 103 | void leaveRoom(String room); 104 | 105 | /** 106 | * Get all rooms a client is joined in. 107 | * 108 | * @return 109 | */ 110 | Set getAllRooms(); 111 | 112 | } 113 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/JsonSupportWrapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import io.netty.buffer.ByteBufInputStream; 19 | import io.netty.buffer.ByteBufOutputStream; 20 | 21 | import java.io.IOException; 22 | import java.util.List; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import com.corundumstudio.socketio.protocol.AckArgs; 28 | import com.corundumstudio.socketio.protocol.JsonSupport; 29 | 30 | class JsonSupportWrapper implements JsonSupport { 31 | 32 | private static final Logger log = LoggerFactory.getLogger(JsonSupportWrapper.class); 33 | 34 | private final JsonSupport delegate; 35 | 36 | JsonSupportWrapper(JsonSupport delegate) { 37 | this.delegate = delegate; 38 | } 39 | 40 | @Override 41 | public AckArgs readAckArgs(ByteBufInputStream src, AckCallback callback) throws IOException { 42 | try { 43 | return delegate.readAckArgs(src, callback); 44 | } catch (Exception e) { 45 | src.reset(); 46 | log.error("Can't read ack args: " + src.readLine() + " for type: " + callback.getResultClass(), e); 47 | throw new IOException(e); 48 | } 49 | } 50 | 51 | @Override 52 | public T readValue(String namespaceName, ByteBufInputStream src, Class valueType) throws IOException { 53 | try { 54 | return delegate.readValue(namespaceName, src, valueType); 55 | } catch (Exception e) { 56 | src.reset(); 57 | log.error("Can't read value: " + src.readLine() + " for type: " + valueType, e); 58 | throw new IOException(e); 59 | } 60 | } 61 | 62 | @Override 63 | public void writeValue(ByteBufOutputStream out, Object value) throws IOException { 64 | try { 65 | delegate.writeValue(out, value); 66 | } catch (Exception e) { 67 | log.error("Can't write value: " + value, e); 68 | throw new IOException(e); 69 | } 70 | } 71 | 72 | @Override 73 | public void addEventMapping(String namespaceName, String eventName, Class ... eventClass) { 74 | delegate.addEventMapping(namespaceName, eventName, eventClass); 75 | } 76 | 77 | @Override 78 | public void removeEventMapping(String namespaceName, String eventName) { 79 | delegate.removeEventMapping(namespaceName, eventName); 80 | } 81 | 82 | @Override 83 | public List getArrays() { 84 | return delegate.getArrays(); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/AckRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.Arrays; 19 | import java.util.List; 20 | import java.util.concurrent.atomic.AtomicBoolean; 21 | 22 | import com.corundumstudio.socketio.listener.DataListener; 23 | import com.corundumstudio.socketio.protocol.Packet; 24 | import com.corundumstudio.socketio.protocol.PacketType; 25 | 26 | /** 27 | * Ack request received from Socket.IO client. 28 | * You can always check is it true through 29 | * {@link #isAckRequested()} method. 30 | * 31 | * You can call {@link #sendAckData} methods only during 32 | * {@link DataListener#onData} invocation. If {@link #sendAckData} 33 | * not called it will be invoked with empty arguments right after 34 | * {@link DataListener#onData} method execution by server. 35 | * 36 | * This object is NOT actual anymore if {@link #sendAckData} was 37 | * executed or {@link DataListener#onData} invocation finished. 38 | * 39 | */ 40 | public class AckRequest { 41 | 42 | private final Packet originalPacket; 43 | private final SocketIOClient client; 44 | private final AtomicBoolean sended = new AtomicBoolean(); 45 | 46 | public AckRequest(Packet originalPacket, SocketIOClient client) { 47 | this.originalPacket = originalPacket; 48 | this.client = client; 49 | } 50 | 51 | /** 52 | * Check whether ack request was made 53 | * 54 | * @return true if ack requested by client 55 | */ 56 | public boolean isAckRequested() { 57 | return originalPacket.isAckRequested(); 58 | } 59 | 60 | /** 61 | * Send ack data to client. 62 | * Can be invoked only once during {@link DataListener#onData} 63 | * method invocation. 64 | * 65 | * @param objs - ack data objects 66 | */ 67 | public void sendAckData(Object ... objs) { 68 | List args = Arrays.asList(objs); 69 | sendAckData(args); 70 | } 71 | 72 | /** 73 | * Send ack data to client. 74 | * Can be invoked only once during {@link DataListener#onData} 75 | * method invocation. 76 | * 77 | * @param objs - ack data object list 78 | */ 79 | public void sendAckData(List objs) { 80 | if (!isAckRequested() || !sended.compareAndSet(false, true)) { 81 | return; 82 | } 83 | Packet ackPacket = new Packet(PacketType.MESSAGE); 84 | ackPacket.setSubType(PacketType.ACK); 85 | ackPacket.setAckId(originalPacket.getAckId()); 86 | ackPacket.setData(objs); 87 | client.send(ackPacket); 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/RedissonPubSubStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import java.util.Queue; 19 | import java.util.concurrent.ConcurrentLinkedQueue; 20 | import java.util.concurrent.ConcurrentMap; 21 | 22 | import org.redisson.api.RTopic; 23 | import org.redisson.api.RedissonClient; 24 | import org.redisson.api.listener.MessageListener; 25 | 26 | import com.corundumstudio.socketio.store.pubsub.PubSubListener; 27 | import com.corundumstudio.socketio.store.pubsub.PubSubMessage; 28 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 29 | import com.corundumstudio.socketio.store.pubsub.PubSubType; 30 | 31 | import io.netty.util.internal.PlatformDependent; 32 | 33 | public class RedissonPubSubStore implements PubSubStore { 34 | 35 | private final RedissonClient redissonPub; 36 | private final RedissonClient redissonSub; 37 | private final Long nodeId; 38 | 39 | private final ConcurrentMap> map = PlatformDependent.newConcurrentHashMap(); 40 | 41 | public RedissonPubSubStore(RedissonClient redissonPub, RedissonClient redissonSub, Long nodeId) { 42 | this.redissonPub = redissonPub; 43 | this.redissonSub = redissonSub; 44 | this.nodeId = nodeId; 45 | } 46 | 47 | @Override 48 | public void publish(PubSubType type, PubSubMessage msg) { 49 | msg.setNodeId(nodeId); 50 | redissonPub.getTopic(type.toString()).publish(msg); 51 | } 52 | 53 | @Override 54 | public void subscribe(PubSubType type, final PubSubListener listener, Class clazz) { 55 | String name = type.toString(); 56 | RTopic topic = redissonSub.getTopic(name); 57 | int regId = topic.addListener(new MessageListener() { 58 | @Override 59 | public void onMessage(String channel, T msg) { 60 | if (!nodeId.equals(msg.getNodeId())) { 61 | listener.onMessage(msg); 62 | } 63 | } 64 | }); 65 | 66 | Queue list = map.get(name); 67 | if (list == null) { 68 | list = new ConcurrentLinkedQueue(); 69 | Queue oldList = map.putIfAbsent(name, list); 70 | if (oldList != null) { 71 | list = oldList; 72 | } 73 | } 74 | list.add(regId); 75 | } 76 | 77 | @Override 78 | public void unsubscribe(PubSubType type) { 79 | String name = type.toString(); 80 | Queue regIds = map.remove(name); 81 | RTopic topic = redissonSub.getTopic(name); 82 | for (Integer id : regIds) { 83 | topic.removeListener(id); 84 | } 85 | } 86 | 87 | @Override 88 | public void shutdown() { 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/SpringAnnotationScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.Method; 20 | import java.util.Arrays; 21 | import java.util.List; 22 | import java.util.concurrent.atomic.AtomicBoolean; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | import org.springframework.beans.BeansException; 27 | import org.springframework.beans.factory.config.BeanPostProcessor; 28 | import org.springframework.util.ReflectionUtils; 29 | import org.springframework.util.ReflectionUtils.MethodCallback; 30 | import org.springframework.util.ReflectionUtils.MethodFilter; 31 | 32 | import com.corundumstudio.socketio.SocketIOServer; 33 | 34 | public class SpringAnnotationScanner implements BeanPostProcessor { 35 | 36 | private static final Logger log = LoggerFactory.getLogger(SpringAnnotationScanner.class); 37 | 38 | private final List> annotations = 39 | Arrays.asList(OnConnect.class, OnDisconnect.class, OnEvent.class); 40 | 41 | private final SocketIOServer socketIOServer; 42 | 43 | private Class originalBeanClass; 44 | 45 | public SpringAnnotationScanner(SocketIOServer socketIOServer) { 46 | super(); 47 | this.socketIOServer = socketIOServer; 48 | } 49 | 50 | @Override 51 | public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 52 | if (originalBeanClass != null) { 53 | socketIOServer.addListeners(bean, originalBeanClass); 54 | log.info("{} bean listeners added", beanName); 55 | originalBeanClass = null; 56 | } 57 | return bean; 58 | } 59 | 60 | @Override 61 | public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 62 | final AtomicBoolean add = new AtomicBoolean(); 63 | ReflectionUtils.doWithMethods(bean.getClass(), 64 | new MethodCallback() { 65 | @Override 66 | public void doWith(Method method) throws IllegalArgumentException, 67 | IllegalAccessException { 68 | add.set(true); 69 | } 70 | }, 71 | new MethodFilter() { 72 | @Override 73 | public boolean matches(Method method) { 74 | for (Class annotationClass : annotations) { 75 | if (method.isAnnotationPresent(annotationClass)) { 76 | return true; 77 | } 78 | } 79 | return false; 80 | } 81 | }); 82 | 83 | if (add.get()) { 84 | originalBeanClass = bean.getClass(); 85 | } 86 | return bean; 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/HazelcastPubSubStore.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store; 17 | 18 | import io.netty.util.internal.PlatformDependent; 19 | 20 | import java.util.Queue; 21 | import java.util.concurrent.ConcurrentLinkedQueue; 22 | import java.util.concurrent.ConcurrentMap; 23 | 24 | import com.corundumstudio.socketio.store.pubsub.PubSubListener; 25 | import com.corundumstudio.socketio.store.pubsub.PubSubMessage; 26 | import com.corundumstudio.socketio.store.pubsub.PubSubStore; 27 | import com.corundumstudio.socketio.store.pubsub.PubSubType; 28 | import com.hazelcast.core.HazelcastInstance; 29 | import com.hazelcast.core.ITopic; 30 | import com.hazelcast.core.Message; 31 | import com.hazelcast.core.MessageListener; 32 | 33 | 34 | public class HazelcastPubSubStore implements PubSubStore { 35 | 36 | private final HazelcastInstance hazelcastPub; 37 | private final HazelcastInstance hazelcastSub; 38 | private final Long nodeId; 39 | 40 | private final ConcurrentMap> map = PlatformDependent.newConcurrentHashMap(); 41 | 42 | public HazelcastPubSubStore(HazelcastInstance hazelcastPub, HazelcastInstance hazelcastSub, Long nodeId) { 43 | this.hazelcastPub = hazelcastPub; 44 | this.hazelcastSub = hazelcastSub; 45 | this.nodeId = nodeId; 46 | } 47 | 48 | @Override 49 | public void publish(PubSubType type, PubSubMessage msg) { 50 | msg.setNodeId(nodeId); 51 | hazelcastPub.getTopic(type.toString()).publish(msg); 52 | } 53 | 54 | @Override 55 | public void subscribe(PubSubType type, final PubSubListener listener, Class clazz) { 56 | String name = type.toString(); 57 | ITopic topic = hazelcastSub.getTopic(name); 58 | String regId = topic.addMessageListener(new MessageListener() { 59 | @Override 60 | public void onMessage(Message message) { 61 | PubSubMessage msg = message.getMessageObject(); 62 | if (!nodeId.equals(msg.getNodeId())) { 63 | listener.onMessage(message.getMessageObject()); 64 | } 65 | } 66 | }); 67 | 68 | Queue list = map.get(name); 69 | if (list == null) { 70 | list = new ConcurrentLinkedQueue(); 71 | Queue oldList = map.putIfAbsent(name, list); 72 | if (oldList != null) { 73 | list = oldList; 74 | } 75 | } 76 | list.add(regId); 77 | } 78 | 79 | @Override 80 | public void unsubscribe(PubSubType type) { 81 | String name = type.toString(); 82 | Queue regIds = map.remove(name); 83 | ITopic topic = hazelcastSub.getTopic(name); 84 | for (String id : regIds) { 85 | topic.removeMessageListener(id); 86 | } 87 | } 88 | 89 | @Override 90 | public void shutdown() { 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/test/java/com/corundumstudio/socketio/parser/PayloadTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.parser; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.buffer.Unpooled; 20 | import io.netty.util.CharsetUtil; 21 | 22 | import java.io.IOException; 23 | import java.util.ArrayList; 24 | import java.util.List; 25 | import java.util.Queue; 26 | import java.util.concurrent.ConcurrentLinkedQueue; 27 | 28 | import org.junit.Assert; 29 | import org.junit.Test; 30 | 31 | import com.corundumstudio.socketio.Configuration; 32 | import com.corundumstudio.socketio.protocol.JacksonJsonSupport; 33 | import com.corundumstudio.socketio.protocol.Packet; 34 | import com.corundumstudio.socketio.protocol.PacketDecoder; 35 | import com.corundumstudio.socketio.protocol.PacketEncoder; 36 | import com.corundumstudio.socketio.protocol.PacketType; 37 | 38 | public class PayloadTest { 39 | 40 | private final JacksonJsonSupport support = new JacksonJsonSupport(); 41 | private final PacketDecoder decoder = new PacketDecoder(support, null); 42 | private final PacketEncoder encoder = new PacketEncoder(new Configuration(), support); 43 | 44 | @Test 45 | public void testPayloadDecode() throws IOException { 46 | ByteBuf buffer = Unpooled.wrappedBuffer("\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::".getBytes()); 47 | List payload = new ArrayList(); 48 | while (buffer.isReadable()) { 49 | Packet packet = decoder.decodePackets(buffer, null); 50 | payload.add(packet); 51 | } 52 | 53 | Assert.assertEquals(3, payload.size()); 54 | Packet msg1 = payload.get(0); 55 | Assert.assertEquals(PacketType.MESSAGE, msg1.getType()); 56 | Assert.assertEquals("5", msg1.getData()); 57 | Packet msg2 = payload.get(1); 58 | Assert.assertEquals(PacketType.MESSAGE, msg2.getType()); 59 | Assert.assertEquals("53d", msg2.getData()); 60 | Packet msg3 = payload.get(2); 61 | Assert.assertEquals(PacketType.DISCONNECT, msg3.getType()); 62 | } 63 | 64 | @Test 65 | public void testPayloadEncode() throws IOException { 66 | Queue packets = new ConcurrentLinkedQueue(); 67 | Packet packet1 = new Packet(PacketType.MESSAGE); 68 | packet1.setData("5"); 69 | packets.add(packet1); 70 | 71 | Packet packet2 = new Packet(PacketType.MESSAGE); 72 | packet2.setData("53d"); 73 | packets.add(packet2); 74 | 75 | ByteBuf result = Unpooled.buffer(); 76 | // encoder.encodePackets(packets, result, UnpooledByteBufAllocator.DEFAULT); 77 | Assert.assertEquals("\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d", result.toString(CharsetUtil.UTF_8)); 78 | } 79 | 80 | @Test 81 | public void testDecodingNewline() throws IOException { 82 | Packet packet = decoder.decodePacket("3:::\n", null); 83 | Assert.assertEquals(PacketType.MESSAGE, packet.getType()); 84 | Assert.assertEquals("\n", packet.getData()); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/scheduler/HashedWheelScheduler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.scheduler; 17 | 18 | import io.netty.channel.ChannelHandlerContext; 19 | import io.netty.util.HashedWheelTimer; 20 | import io.netty.util.Timeout; 21 | import io.netty.util.TimerTask; 22 | import io.netty.util.internal.PlatformDependent; 23 | 24 | import java.util.Map; 25 | import java.util.concurrent.TimeUnit; 26 | 27 | public class HashedWheelScheduler implements CancelableScheduler { 28 | 29 | private final Map scheduledFutures = PlatformDependent.newConcurrentHashMap(); 30 | private final HashedWheelTimer executorService = new HashedWheelTimer(); 31 | 32 | private volatile ChannelHandlerContext ctx; 33 | 34 | @Override 35 | public void update(ChannelHandlerContext ctx) { 36 | this.ctx = ctx; 37 | } 38 | 39 | @Override 40 | public void cancel(SchedulerKey key) { 41 | Timeout timeout = scheduledFutures.remove(key); 42 | if (timeout != null) { 43 | timeout.cancel(); 44 | } 45 | } 46 | 47 | @Override 48 | public void schedule(final Runnable runnable, long delay, TimeUnit unit) { 49 | executorService.newTimeout(new TimerTask() { 50 | @Override 51 | public void run(Timeout timeout) throws Exception { 52 | runnable.run(); 53 | } 54 | }, delay, unit); 55 | } 56 | 57 | @Override 58 | public void scheduleCallback(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) { 59 | Timeout timeout = executorService.newTimeout(new TimerTask() { 60 | @Override 61 | public void run(Timeout timeout) throws Exception { 62 | ctx.executor().execute(new Runnable() { 63 | @Override 64 | public void run() { 65 | try { 66 | runnable.run(); 67 | } finally { 68 | scheduledFutures.remove(key); 69 | } 70 | } 71 | }); 72 | } 73 | }, delay, unit); 74 | 75 | if (!timeout.isExpired()) { 76 | scheduledFutures.put(key, timeout); 77 | } 78 | } 79 | 80 | @Override 81 | public void schedule(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) { 82 | Timeout timeout = executorService.newTimeout(new TimerTask() { 83 | @Override 84 | public void run(Timeout timeout) throws Exception { 85 | try { 86 | runnable.run(); 87 | } finally { 88 | scheduledFutures.remove(key); 89 | } 90 | } 91 | }, delay, unit); 92 | 93 | if (!timeout.isExpired()) { 94 | scheduledFutures.put(key, timeout); 95 | } 96 | } 97 | 98 | @Override 99 | public void shutdown() { 100 | executorService.stop(); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/HandshakeData.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.io.Serializable; 19 | import java.net.InetSocketAddress; 20 | import java.util.Date; 21 | import java.util.HashMap; 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | import io.netty.handler.codec.http.HttpHeaders; 26 | 27 | public class HandshakeData implements Serializable { 28 | 29 | private static final long serialVersionUID = 1196350300161819978L; 30 | 31 | private HttpHeaders headers; 32 | private InetSocketAddress address; 33 | private Date time = new Date(); 34 | private String url; 35 | private Map> urlParams; 36 | private boolean xdomain; 37 | 38 | // needed for correct deserialization 39 | public HandshakeData() { 40 | } 41 | 42 | public HandshakeData(HttpHeaders headers, Map> urlParams, InetSocketAddress address, String url, boolean xdomain) { 43 | super(); 44 | this.headers = headers; 45 | this.urlParams = urlParams; 46 | this.address = address; 47 | this.url = url; 48 | this.xdomain = xdomain; 49 | } 50 | 51 | /** 52 | * Client network address 53 | * 54 | * @return 55 | */ 56 | public InetSocketAddress getAddress() { 57 | return address; 58 | } 59 | 60 | /** 61 | * Http headers sent during first client request 62 | * 63 | * @return 64 | */ 65 | public HttpHeaders getHttpHeaders() { 66 | return headers; 67 | } 68 | 69 | /** 70 | * Use {@link #getHttpHeaders()} 71 | */ 72 | @Deprecated 73 | public Map> getHeaders() { 74 | Map> result = new HashMap>(headers.names().size()); 75 | for (String name : headers.names()) { 76 | List values = headers.getAll(name); 77 | result.put(name, values); 78 | } 79 | return result; 80 | } 81 | 82 | /** 83 | * Use {@link #getHttpHeaders().get()} 84 | */ 85 | @Deprecated 86 | public String getSingleHeader(String name) { 87 | return headers.get(name); 88 | } 89 | 90 | /** 91 | * Client connection date 92 | * 93 | * @return 94 | */ 95 | public Date getTime() { 96 | return time; 97 | } 98 | 99 | /** 100 | * Url used by client during first request 101 | * 102 | * @return 103 | */ 104 | public String getUrl() { 105 | return url; 106 | } 107 | 108 | public boolean isXdomain() { 109 | return xdomain; 110 | } 111 | 112 | /** 113 | * Url params stored in url used by client during first request 114 | * 115 | * @return 116 | */ 117 | public Map> getUrlParams() { 118 | return urlParams; 119 | } 120 | 121 | public String getSingleUrlParam(String name) { 122 | List values = urlParams.get(name); 123 | if (values != null && values.size() == 1) { 124 | return values.iterator().next(); 125 | } 126 | return null; 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/Packet.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | 20 | import java.io.Serializable; 21 | import java.util.ArrayList; 22 | import java.util.Collections; 23 | import java.util.List; 24 | 25 | import com.corundumstudio.socketio.namespace.Namespace; 26 | 27 | public class Packet implements Serializable { 28 | 29 | private static final long serialVersionUID = 4560159536486711426L; 30 | 31 | private PacketType type; 32 | private PacketType subType; 33 | private Long ackId; 34 | private String name; 35 | private String nsp = Namespace.DEFAULT_NAME; 36 | private Object data; 37 | 38 | private ByteBuf dataSource; 39 | private int attachmentsCount; 40 | private List attachments = Collections.emptyList(); 41 | 42 | protected Packet() { 43 | } 44 | 45 | public Packet(PacketType type) { 46 | super(); 47 | this.type = type; 48 | } 49 | 50 | public PacketType getSubType() { 51 | return subType; 52 | } 53 | 54 | public void setSubType(PacketType subType) { 55 | this.subType = subType; 56 | } 57 | 58 | public PacketType getType() { 59 | return type; 60 | } 61 | 62 | public void setData(Object data) { 63 | this.data = data; 64 | } 65 | 66 | /** 67 | * Get packet data 68 | *
 69 |      * @return json object for {@link PacketType.JSON} type
 70 |      * message for {@link PacketType.MESSAGE} type
 71 |      * 
72 | */ 73 | public T getData() { 74 | return (T)data; 75 | } 76 | 77 | public void setNsp(String endpoint) { 78 | this.nsp = endpoint; 79 | } 80 | 81 | public String getNsp() { 82 | return nsp; 83 | } 84 | 85 | public String getName() { 86 | return name; 87 | } 88 | 89 | public void setName(String name) { 90 | this.name = name; 91 | } 92 | 93 | public Long getAckId() { 94 | return ackId; 95 | } 96 | 97 | public void setAckId(Long ackId) { 98 | this.ackId = ackId; 99 | } 100 | 101 | public boolean isAckRequested() { 102 | return getAckId() != null; 103 | } 104 | 105 | public void initAttachments(int attachmentsCount) { 106 | this.attachmentsCount = attachmentsCount; 107 | this.attachments = new ArrayList(attachmentsCount); 108 | } 109 | public void addAttachment(ByteBuf attachment) { 110 | if (this.attachments.size() < attachmentsCount) { 111 | this.attachments.add(attachment); 112 | } 113 | } 114 | public List getAttachments() { 115 | return attachments; 116 | } 117 | public boolean hasAttachments() { 118 | return attachmentsCount != 0; 119 | } 120 | public boolean isAttachmentsLoaded() { 121 | return this.attachments.size() == attachmentsCount; 122 | } 123 | 124 | public ByteBuf getDataSource() { 125 | return dataSource; 126 | } 127 | public void setDataSource(ByteBuf dataSource) { 128 | this.dataSource = dataSource; 129 | } 130 | 131 | @Override 132 | public String toString() { 133 | return "Packet [type=" + type + ", ackId=" + ackId + "]"; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/store/pubsub/BaseStoreFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.store.pubsub; 17 | 18 | import org.slf4j.Logger; 19 | import org.slf4j.LoggerFactory; 20 | 21 | import com.corundumstudio.socketio.handler.AuthorizeHandler; 22 | import com.corundumstudio.socketio.handler.ClientHead; 23 | import com.corundumstudio.socketio.namespace.NamespacesHub; 24 | import com.corundumstudio.socketio.protocol.JsonSupport; 25 | import com.corundumstudio.socketio.store.StoreFactory; 26 | 27 | public abstract class BaseStoreFactory implements StoreFactory { 28 | 29 | private final Logger log = LoggerFactory.getLogger(getClass()); 30 | 31 | private Long nodeId = (long) (Math.random() * 1000000); 32 | 33 | protected Long getNodeId() { 34 | return nodeId; 35 | } 36 | 37 | @Override 38 | public void init(final NamespacesHub namespacesHub, final AuthorizeHandler authorizeHandler, JsonSupport jsonSupport) { 39 | pubSubStore().subscribe(PubSubType.DISCONNECT, new PubSubListener() { 40 | @Override 41 | public void onMessage(DisconnectMessage msg) { 42 | log.debug("{} sessionId: {}", PubSubType.DISCONNECT, msg.getSessionId()); 43 | } 44 | }, DisconnectMessage.class); 45 | 46 | pubSubStore().subscribe(PubSubType.CONNECT, new PubSubListener() { 47 | @Override 48 | public void onMessage(ConnectMessage msg) { 49 | authorizeHandler.connect(msg.getSessionId()); 50 | log.debug("{} sessionId: {}", PubSubType.CONNECT, msg.getSessionId()); 51 | } 52 | }, ConnectMessage.class); 53 | 54 | pubSubStore().subscribe(PubSubType.DISPATCH, new PubSubListener() { 55 | @Override 56 | public void onMessage(DispatchMessage msg) { 57 | String name = msg.getRoom(); 58 | 59 | namespacesHub.get(msg.getNamespace()).dispatch(name, msg.getPacket()); 60 | log.debug("{} packet: {}", PubSubType.DISPATCH, msg.getPacket()); 61 | } 62 | }, DispatchMessage.class); 63 | 64 | pubSubStore().subscribe(PubSubType.JOIN, new PubSubListener() { 65 | @Override 66 | public void onMessage(JoinLeaveMessage msg) { 67 | String name = msg.getRoom(); 68 | 69 | namespacesHub.get(msg.getNamespace()).join(name, msg.getSessionId()); 70 | log.debug("{} sessionId: {}", PubSubType.JOIN, msg.getSessionId()); 71 | } 72 | }, JoinLeaveMessage.class); 73 | 74 | pubSubStore().subscribe(PubSubType.LEAVE, new PubSubListener() { 75 | @Override 76 | public void onMessage(JoinLeaveMessage msg) { 77 | String name = msg.getRoom(); 78 | 79 | namespacesHub.get(msg.getNamespace()).leave(name, msg.getSessionId()); 80 | log.debug("{} sessionId: {}", PubSubType.LEAVE, msg.getSessionId()); 81 | } 82 | }, JoinLeaveMessage.class); 83 | } 84 | 85 | @Override 86 | public abstract PubSubStore pubSubStore(); 87 | 88 | @Override 89 | public void onDisconnect(ClientHead client) { 90 | } 91 | 92 | @Override 93 | public String toString() { 94 | return getClass().getSimpleName() + " (distributed session store, distributed publish/subscribe)"; 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/ScannerEngine.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.Method; 20 | import java.lang.reflect.Modifier; 21 | import java.util.Arrays; 22 | import java.util.List; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import com.corundumstudio.socketio.namespace.Namespace; 28 | 29 | public class ScannerEngine { 30 | 31 | private static final Logger log = LoggerFactory.getLogger(ScannerEngine.class); 32 | 33 | private static final List annotations = 34 | Arrays.asList(new OnConnectScanner(), new OnDisconnectScanner(), new OnEventScanner()); 35 | 36 | private Method findSimilarMethod(Class objectClazz, Method method) { 37 | Method[] methods = objectClazz.getDeclaredMethods(); 38 | for (Method m : methods) { 39 | if (isEquals(m, method)) { 40 | return m; 41 | } 42 | } 43 | return null; 44 | } 45 | 46 | public void scan(Namespace namespace, Object object, Class clazz) 47 | throws IllegalArgumentException { 48 | Method[] methods = clazz.getDeclaredMethods(); 49 | 50 | if (!clazz.isAssignableFrom(object.getClass())) { 51 | for (Method method : methods) { 52 | for (AnnotationScanner annotationScanner : annotations) { 53 | Annotation ann = method.getAnnotation(annotationScanner.getScanAnnotation()); 54 | if (ann != null) { 55 | annotationScanner.validate(method, clazz); 56 | 57 | Method m = findSimilarMethod(object.getClass(), method); 58 | if (m != null) { 59 | annotationScanner.addListener(namespace, object, m, ann); 60 | } else { 61 | log.warn("Method similar to " + method.getName() + " can't be found in " + object.getClass()); 62 | } 63 | } 64 | } 65 | } 66 | } else { 67 | for (Method method : methods) { 68 | for (AnnotationScanner annotationScanner : annotations) { 69 | Annotation ann = method.getAnnotation(annotationScanner.getScanAnnotation()); 70 | if (ann != null) { 71 | annotationScanner.validate(method, clazz); 72 | makeAccessible(method); 73 | annotationScanner.addListener(namespace, object, method, ann); 74 | } 75 | } 76 | } 77 | 78 | if (clazz.getSuperclass() != null) { 79 | scan(namespace, object, clazz.getSuperclass()); 80 | } else if (clazz.isInterface()) { 81 | for (Class superIfc : clazz.getInterfaces()) { 82 | scan(namespace, object, superIfc); 83 | } 84 | } 85 | } 86 | 87 | } 88 | 89 | private boolean isEquals(Method method1, Method method2) { 90 | if (!method1.getName().equals(method2.getName()) 91 | || !method1.getReturnType().equals(method2.getReturnType())) { 92 | return false; 93 | } 94 | 95 | return Arrays.equals(method1.getParameterTypes(), method2.getParameterTypes()); 96 | } 97 | 98 | private void makeAccessible(Method method) { 99 | if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) 100 | && !method.isAccessible()) { 101 | method.setAccessible(true); 102 | } 103 | } 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/protocol/UTF8CharsScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.protocol; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | 20 | public class UTF8CharsScanner { 21 | 22 | /** 23 | * Lookup table used for determining which input characters need special 24 | * handling when contained in text segment. 25 | */ 26 | static final int[] sInputCodes; 27 | static { 28 | /* 29 | * 96 would do for most cases (backslash is ascii 94) but if we want to 30 | * do lookups by raw bytes it's better to have full table 31 | */ 32 | int[] table = new int[256]; 33 | // Control chars and non-space white space are not allowed unquoted 34 | for (int i = 0; i < 32; ++i) { 35 | table[i] = -1; 36 | } 37 | // And then string end and quote markers are special too 38 | table['"'] = 1; 39 | table['\\'] = 1; 40 | sInputCodes = table; 41 | } 42 | 43 | /** 44 | * Additionally we can combine UTF-8 decoding info into similar data table. 45 | */ 46 | static final int[] sInputCodesUtf8; 47 | static { 48 | int[] table = new int[sInputCodes.length]; 49 | System.arraycopy(sInputCodes, 0, table, 0, sInputCodes.length); 50 | for (int c = 128; c < 256; ++c) { 51 | int code; 52 | 53 | // We'll add number of bytes needed for decoding 54 | if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) 55 | code = 2; 56 | } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) 57 | code = 3; 58 | } else if ((c & 0xF8) == 0xF0) { 59 | // 4 bytes; double-char with surrogates and all... 60 | code = 4; 61 | } else { 62 | // And -1 seems like a good "universal" error marker... 63 | code = -1; 64 | } 65 | table[c] = code; 66 | } 67 | sInputCodesUtf8 = table; 68 | } 69 | 70 | private int getCharTailIndex(ByteBuf inputBuffer, int i) { 71 | int c = (int) inputBuffer.getByte(i) & 0xFF; 72 | switch (sInputCodesUtf8[c]) { 73 | case 2: // 2-byte UTF 74 | i += 2; 75 | break; 76 | case 3: // 3-byte UTF 77 | i += 3; 78 | break; 79 | case 4: // 4-byte UTF 80 | i += 4; 81 | break; 82 | default: 83 | i++; 84 | break; 85 | } 86 | return i; 87 | } 88 | 89 | public int getLength(ByteBuf inputBuffer, int start) { 90 | int len = 0; 91 | for (int i = start; i < inputBuffer.writerIndex();) { 92 | i = getCharTailIndex(inputBuffer, i); 93 | len++; 94 | } 95 | return len; 96 | } 97 | 98 | public int getActualLength(ByteBuf inputBuffer, int length) { 99 | int len = 0; 100 | int start = inputBuffer.readerIndex(); 101 | for (int i = inputBuffer.readerIndex(); i < inputBuffer.readableBytes() + inputBuffer.readerIndex();) { 102 | i = getCharTailIndex(inputBuffer, i); 103 | len++; 104 | if (length == len) { 105 | return i-start; 106 | } 107 | } 108 | throw new IllegalStateException(); 109 | } 110 | 111 | 112 | public int findTailIndex(ByteBuf inputBuffer, int start, int end, 113 | int charsToRead) { 114 | int len = 0; 115 | int i = start; 116 | while (i < end) { 117 | i = getCharTailIndex(inputBuffer, i); 118 | len++; 119 | if (charsToRead == len) { 120 | break; 121 | } 122 | } 123 | return i; 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/scheduler/HashedWheelTimeoutScheduler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | /** 17 | * Modified version of HashedWheelScheduler specially for timeouts handling. 18 | * Difference: 19 | * - handling old timeout with same key after adding new one 20 | * fixes multithreaded problem that appears in highly concurrent non-atomic sequence cancel() -> schedule() 21 | * 22 | * (c) Alim Akbashev, 2015-02-11 23 | */ 24 | 25 | package com.corundumstudio.socketio.scheduler; 26 | 27 | import io.netty.channel.ChannelHandlerContext; 28 | import io.netty.util.HashedWheelTimer; 29 | import io.netty.util.Timeout; 30 | import io.netty.util.TimerTask; 31 | import io.netty.util.internal.PlatformDependent; 32 | 33 | import java.util.concurrent.ConcurrentMap; 34 | import java.util.concurrent.TimeUnit; 35 | 36 | public class HashedWheelTimeoutScheduler implements CancelableScheduler { 37 | 38 | private final ConcurrentMap scheduledFutures = PlatformDependent.newConcurrentHashMap(); 39 | private final HashedWheelTimer executorService = new HashedWheelTimer(); 40 | 41 | private volatile ChannelHandlerContext ctx; 42 | 43 | @Override 44 | public void update(ChannelHandlerContext ctx) { 45 | this.ctx = ctx; 46 | } 47 | 48 | @Override 49 | public void cancel(SchedulerKey key) { 50 | Timeout timeout = scheduledFutures.remove(key); 51 | if (timeout != null) { 52 | timeout.cancel(); 53 | } 54 | } 55 | 56 | @Override 57 | public void schedule(final Runnable runnable, long delay, TimeUnit unit) { 58 | executorService.newTimeout(new TimerTask() { 59 | @Override 60 | public void run(Timeout timeout) throws Exception { 61 | runnable.run(); 62 | } 63 | }, delay, unit); 64 | } 65 | 66 | @Override 67 | public void scheduleCallback(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) { 68 | Timeout timeout = executorService.newTimeout(new TimerTask() { 69 | @Override 70 | public void run(Timeout timeout) throws Exception { 71 | ctx.executor().execute(new Runnable() { 72 | @Override 73 | public void run() { 74 | try { 75 | runnable.run(); 76 | } finally { 77 | scheduledFutures.remove(key); 78 | } 79 | } 80 | }); 81 | } 82 | }, delay, unit); 83 | 84 | replaceScheduledFuture(key, timeout); 85 | } 86 | 87 | @Override 88 | public void schedule(final SchedulerKey key, final Runnable runnable, long delay, TimeUnit unit) { 89 | Timeout timeout = executorService.newTimeout(new TimerTask() { 90 | @Override 91 | public void run(Timeout timeout) throws Exception { 92 | try { 93 | runnable.run(); 94 | } finally { 95 | scheduledFutures.remove(key); 96 | } 97 | } 98 | }, delay, unit); 99 | 100 | replaceScheduledFuture(key, timeout); 101 | } 102 | 103 | @Override 104 | public void shutdown() { 105 | executorService.stop(); 106 | } 107 | 108 | private void replaceScheduledFuture(final SchedulerKey key, final Timeout newTimeout) { 109 | final Timeout oldTimeout; 110 | 111 | if (newTimeout.isExpired()) { 112 | // no need to put already expired timeout to scheduledFutures map. 113 | // simply remove old timeout 114 | oldTimeout = scheduledFutures.remove(key); 115 | } else { 116 | oldTimeout = scheduledFutures.put(key, newTimeout); 117 | } 118 | 119 | // if there was old timeout, cancel it 120 | if (oldTimeout != null) { 121 | oldTimeout.cancel(); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/PacketListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import java.util.Collections; 19 | import java.util.List; 20 | 21 | import com.corundumstudio.socketio.AckRequest; 22 | import com.corundumstudio.socketio.Transport; 23 | import com.corundumstudio.socketio.ack.AckManager; 24 | import com.corundumstudio.socketio.namespace.Namespace; 25 | import com.corundumstudio.socketio.namespace.NamespacesHub; 26 | import com.corundumstudio.socketio.protocol.Packet; 27 | import com.corundumstudio.socketio.protocol.PacketType; 28 | import com.corundumstudio.socketio.scheduler.CancelableScheduler; 29 | import com.corundumstudio.socketio.scheduler.SchedulerKey; 30 | import com.corundumstudio.socketio.transport.NamespaceClient; 31 | import com.corundumstudio.socketio.transport.PollingTransport; 32 | 33 | public class PacketListener { 34 | 35 | private final NamespacesHub namespacesHub; 36 | private final AckManager ackManager; 37 | private final CancelableScheduler scheduler; 38 | 39 | public PacketListener(AckManager ackManager, NamespacesHub namespacesHub, PollingTransport xhrPollingTransport, 40 | CancelableScheduler scheduler) { 41 | this.ackManager = ackManager; 42 | this.namespacesHub = namespacesHub; 43 | this.scheduler = scheduler; 44 | } 45 | 46 | public void onPacket(Packet packet, NamespaceClient client, Transport transport) { 47 | final AckRequest ackRequest = new AckRequest(packet, client); 48 | 49 | if (packet.isAckRequested()) { 50 | ackManager.initAckIndex(client.getSessionId(), packet.getAckId()); 51 | } 52 | 53 | switch (packet.getType()) { 54 | case PING: { 55 | Packet outPacket = new Packet(PacketType.PONG); 56 | outPacket.setData(packet.getData()); 57 | // TODO use future 58 | client.getBaseClient().send(outPacket, transport); 59 | 60 | if ("probe".equals(packet.getData())) { 61 | client.getBaseClient().send(new Packet(PacketType.NOOP), Transport.POLLING); 62 | } else { 63 | client.getBaseClient().schedulePingTimeout(); 64 | } 65 | break; 66 | } 67 | 68 | case UPGRADE: { 69 | client.getBaseClient().schedulePingTimeout(); 70 | 71 | SchedulerKey key = new SchedulerKey(SchedulerKey.Type.UPGRADE_TIMEOUT, client.getSessionId()); 72 | scheduler.cancel(key); 73 | 74 | client.getBaseClient().upgradeCurrentTransport(transport); 75 | break; 76 | } 77 | 78 | case MESSAGE: { 79 | client.getBaseClient().schedulePingTimeout(); 80 | 81 | if (packet.getSubType() == PacketType.DISCONNECT) { 82 | client.onDisconnect(); 83 | } 84 | 85 | if (packet.getSubType() == PacketType.CONNECT) { 86 | Namespace namespace = namespacesHub.get(packet.getNsp()); 87 | namespace.onConnect(client); 88 | // send connect handshake packet back to client 89 | client.getBaseClient().send(packet, transport); 90 | } 91 | 92 | if (packet.getSubType() == PacketType.ACK) { 93 | ackManager.onAck(client, packet); 94 | } 95 | 96 | if (packet.getSubType() == PacketType.EVENT 97 | || packet.getSubType() == PacketType.BINARY_EVENT) { 98 | Namespace namespace = namespacesHub.get(packet.getNsp()); 99 | List args = Collections.emptyList(); 100 | if (packet.getData() != null) { 101 | args = packet.getData(); 102 | } 103 | namespace.onEvent(client, packet.getName(), args, ackRequest); 104 | } 105 | break; 106 | } 107 | 108 | case CLOSE: 109 | client.getBaseClient().onChannelDisconnect(); 110 | break; 111 | 112 | default: 113 | break; 114 | } 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/handler/InPacketHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.handler; 17 | 18 | import io.netty.buffer.ByteBuf; 19 | import io.netty.channel.ChannelHandler.Sharable; 20 | import io.netty.channel.ChannelHandlerContext; 21 | import io.netty.channel.SimpleChannelInboundHandler; 22 | import io.netty.util.CharsetUtil; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import com.corundumstudio.socketio.listener.ExceptionListener; 28 | import com.corundumstudio.socketio.messages.PacketsMessage; 29 | import com.corundumstudio.socketio.namespace.Namespace; 30 | import com.corundumstudio.socketio.namespace.NamespacesHub; 31 | import com.corundumstudio.socketio.protocol.Packet; 32 | import com.corundumstudio.socketio.protocol.PacketDecoder; 33 | import com.corundumstudio.socketio.protocol.PacketType; 34 | import com.corundumstudio.socketio.transport.NamespaceClient; 35 | 36 | @Sharable 37 | public class InPacketHandler extends SimpleChannelInboundHandler { 38 | 39 | private static final Logger log = LoggerFactory.getLogger(InPacketHandler.class); 40 | 41 | private final PacketListener packetListener; 42 | private final PacketDecoder decoder; 43 | private final NamespacesHub namespacesHub; 44 | private final ExceptionListener exceptionListener; 45 | 46 | public InPacketHandler(PacketListener packetListener, PacketDecoder decoder, NamespacesHub namespacesHub, ExceptionListener exceptionListener) { 47 | super(); 48 | this.packetListener = packetListener; 49 | this.decoder = decoder; 50 | this.namespacesHub = namespacesHub; 51 | this.exceptionListener = exceptionListener; 52 | } 53 | 54 | @Override 55 | protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, PacketsMessage message) 56 | throws Exception { 57 | ByteBuf content = message.getContent(); 58 | ClientHead client = message.getClient(); 59 | 60 | if (log.isTraceEnabled()) { 61 | log.trace("In message: {} sessionId: {}", content.toString(CharsetUtil.UTF_8), client.getSessionId()); 62 | } 63 | while (content.isReadable()) { 64 | try { 65 | Packet packet = decoder.decodePackets(content, client); 66 | if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) { 67 | return; 68 | } 69 | Namespace ns = namespacesHub.get(packet.getNsp()); 70 | if (ns == null) { 71 | if (packet.getSubType() == PacketType.CONNECT) { 72 | Packet p = new Packet(PacketType.MESSAGE); 73 | p.setSubType(PacketType.ERROR); 74 | p.setNsp(packet.getNsp()); 75 | p.setData("Invalid namespace"); 76 | client.send(p); 77 | return; 78 | } 79 | log.debug("Can't find namespace for endpoint: {}, sessionId: {} probably it was removed.", packet.getNsp(), client.getSessionId()); 80 | return; 81 | } 82 | 83 | if (packet.getSubType() == PacketType.CONNECT) { 84 | client.addNamespaceClient(ns); 85 | } 86 | 87 | NamespaceClient nClient = client.getChildClient(ns); 88 | if (nClient == null) { 89 | log.debug("Can't find namespace client in namespace: {}, sessionId: {} probably it was disconnected.", ns.getName(), client.getSessionId()); 90 | return; 91 | } 92 | packetListener.onPacket(packet, nClient, message.getTransport()); 93 | } catch (Exception ex) { 94 | String c = content.toString(CharsetUtil.UTF_8); 95 | log.error("Error during data processing. Client sessionId: " + client.getSessionId() + ", data: " + c, ex); 96 | throw ex; 97 | } 98 | } 99 | } 100 | 101 | @Override 102 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception { 103 | if (!exceptionListener.exceptionCaught(ctx, e)) { 104 | super.exceptionCaught(ctx, e); 105 | } 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/BroadcastOperations.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio; 17 | 18 | import java.util.Arrays; 19 | import java.util.Collection; 20 | import java.util.HashMap; 21 | import java.util.HashSet; 22 | import java.util.Map; 23 | import java.util.Map.Entry; 24 | import java.util.Set; 25 | 26 | import com.corundumstudio.socketio.misc.IterableCollection; 27 | import com.corundumstudio.socketio.namespace.Namespace; 28 | import com.corundumstudio.socketio.protocol.Packet; 29 | import com.corundumstudio.socketio.protocol.PacketType; 30 | import com.corundumstudio.socketio.store.StoreFactory; 31 | import com.corundumstudio.socketio.store.pubsub.DispatchMessage; 32 | import com.corundumstudio.socketio.store.pubsub.PubSubType; 33 | 34 | /** 35 | * Fully thread-safe. 36 | * 37 | */ 38 | public class BroadcastOperations implements ClientOperations { 39 | 40 | private final Iterable clients; 41 | private final StoreFactory storeFactory; 42 | 43 | public BroadcastOperations(Iterable clients, StoreFactory storeFactory) { 44 | super(); 45 | this.clients = clients; 46 | this.storeFactory = storeFactory; 47 | } 48 | 49 | private void dispatch(Packet packet) { 50 | Map> namespaceRooms = new HashMap>(); 51 | for (SocketIOClient socketIOClient : clients) { 52 | Namespace namespace = (Namespace)socketIOClient.getNamespace(); 53 | Set rooms = namespace.getRooms(socketIOClient); 54 | 55 | Set roomsList = namespaceRooms.get(namespace.getName()); 56 | if (roomsList == null) { 57 | roomsList = new HashSet(); 58 | namespaceRooms.put(namespace.getName(), roomsList); 59 | } 60 | roomsList.addAll(rooms); 61 | } 62 | for (Entry> entry : namespaceRooms.entrySet()) { 63 | for (String room : entry.getValue()) { 64 | storeFactory.pubSubStore().publish(PubSubType.DISPATCH, new DispatchMessage(room, packet, entry.getKey())); 65 | } 66 | } 67 | } 68 | 69 | public Collection getClients() { 70 | return new IterableCollection(clients); 71 | } 72 | 73 | @Override 74 | public void send(Packet packet) { 75 | for (SocketIOClient client : clients) { 76 | client.send(packet); 77 | } 78 | dispatch(packet); 79 | } 80 | 81 | public void send(Packet packet, BroadcastAckCallback ackCallback) { 82 | for (SocketIOClient client : clients) { 83 | client.send(packet, ackCallback.createClientCallback(client)); 84 | } 85 | ackCallback.loopFinished(); 86 | } 87 | 88 | @Override 89 | public void disconnect() { 90 | for (SocketIOClient client : clients) { 91 | client.disconnect(); 92 | } 93 | } 94 | 95 | public void sendEvent(String name, SocketIOClient excludedClient, Object... data) { 96 | Packet packet = new Packet(PacketType.MESSAGE); 97 | packet.setSubType(PacketType.EVENT); 98 | packet.setName(name); 99 | packet.setData(Arrays.asList(data)); 100 | 101 | for (SocketIOClient client : clients) { 102 | if (client.getSessionId().equals(excludedClient.getSessionId())) { 103 | continue; 104 | } 105 | client.send(packet); 106 | } 107 | dispatch(packet); 108 | } 109 | 110 | @Override 111 | public void sendEvent(String name, Object... data) { 112 | Packet packet = new Packet(PacketType.MESSAGE); 113 | packet.setSubType(PacketType.EVENT); 114 | packet.setName(name); 115 | packet.setData(Arrays.asList(data)); 116 | send(packet); 117 | } 118 | 119 | public void sendEvent(String name, Object data, BroadcastAckCallback ackCallback) { 120 | for (SocketIOClient client : clients) { 121 | client.sendEvent(name, ackCallback.createClientCallback(client), data); 122 | } 123 | ackCallback.loopFinished(); 124 | } 125 | 126 | public void sendEvent(String name, Object data, SocketIOClient excludedClient, BroadcastAckCallback ackCallback) { 127 | for (SocketIOClient client : clients) { 128 | if (client.getSessionId().equals(excludedClient.getSessionId())) { 129 | continue; 130 | } 131 | client.sendEvent(name, ackCallback.createClientCallback(client), data); 132 | } 133 | ackCallback.loopFinished(); 134 | } 135 | 136 | 137 | } 138 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/annotation/OnEventScanner.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.annotation; 17 | 18 | import java.lang.annotation.Annotation; 19 | import java.lang.reflect.InvocationTargetException; 20 | import java.lang.reflect.Method; 21 | import java.util.ArrayList; 22 | import java.util.List; 23 | 24 | import com.corundumstudio.socketio.AckRequest; 25 | import com.corundumstudio.socketio.MultiTypeArgs; 26 | import com.corundumstudio.socketio.SocketIOClient; 27 | import com.corundumstudio.socketio.handler.SocketIOException; 28 | import com.corundumstudio.socketio.listener.DataListener; 29 | import com.corundumstudio.socketio.listener.MultiTypeEventListener; 30 | import com.corundumstudio.socketio.namespace.Namespace; 31 | 32 | public class OnEventScanner implements AnnotationScanner { 33 | 34 | @Override 35 | public Class getScanAnnotation() { 36 | return OnEvent.class; 37 | } 38 | 39 | @Override 40 | @SuppressWarnings("unchecked") 41 | public void addListener(Namespace namespace, final Object object, final Method method, Annotation annot) { 42 | OnEvent annotation = (OnEvent) annot; 43 | if (annotation.value() == null || annotation.value().trim().length() == 0) { 44 | throw new IllegalArgumentException("OnEvent \"value\" parameter is required"); 45 | } 46 | final int socketIOClientIndex = paramIndex(method, SocketIOClient.class); 47 | final int ackRequestIndex = paramIndex(method, AckRequest.class); 48 | final List dataIndexes = dataIndexes(method); 49 | 50 | if (dataIndexes.size() > 1) { 51 | List> classes = new ArrayList>(); 52 | for (int index : dataIndexes) { 53 | Class param = method.getParameterTypes()[index]; 54 | classes.add(param); 55 | } 56 | 57 | namespace.addMultiTypeEventListener(annotation.value(), new MultiTypeEventListener() { 58 | @Override 59 | public void onData(SocketIOClient client, MultiTypeArgs data, AckRequest ackSender) { 60 | try { 61 | Object[] args = new Object[method.getParameterTypes().length]; 62 | if (socketIOClientIndex != -1) { 63 | args[socketIOClientIndex] = client; 64 | } 65 | if (ackRequestIndex != -1) { 66 | args[ackRequestIndex] = ackSender; 67 | } 68 | int i = 0; 69 | for (int index : dataIndexes) { 70 | args[index] = data.get(i); 71 | i++; 72 | } 73 | method.invoke(object, args); 74 | } catch (InvocationTargetException e) { 75 | throw new SocketIOException(e.getCause()); 76 | } catch (Exception e) { 77 | throw new SocketIOException(e); 78 | } 79 | } 80 | }, classes.toArray(new Class[classes.size()])); 81 | } else { 82 | Class objectType = Void.class; 83 | if (!dataIndexes.isEmpty()) { 84 | objectType = method.getParameterTypes()[dataIndexes.iterator().next()]; 85 | } 86 | 87 | namespace.addEventListener(annotation.value(), objectType, new DataListener() { 88 | @Override 89 | public void onData(SocketIOClient client, Object data, AckRequest ackSender) { 90 | try { 91 | Object[] args = new Object[method.getParameterTypes().length]; 92 | if (socketIOClientIndex != -1) { 93 | args[socketIOClientIndex] = client; 94 | } 95 | if (ackRequestIndex != -1) { 96 | args[ackRequestIndex] = ackSender; 97 | } 98 | if (!dataIndexes.isEmpty()) { 99 | int dataIndex = dataIndexes.iterator().next(); 100 | args[dataIndex] = data; 101 | } 102 | method.invoke(object, args); 103 | } catch (InvocationTargetException e) { 104 | throw new SocketIOException(e.getCause()); 105 | } catch (Exception e) { 106 | throw new SocketIOException(e); 107 | } 108 | } 109 | }); 110 | } 111 | } 112 | 113 | private List dataIndexes(Method method) { 114 | List result = new ArrayList(); 115 | int index = 0; 116 | for (Class type : method.getParameterTypes()) { 117 | if (!type.equals(AckRequest.class) && !type.equals(SocketIOClient.class)) { 118 | result.add(index); 119 | } 120 | index++; 121 | } 122 | return result; 123 | } 124 | 125 | private int paramIndex(Method method, Class clazz) { 126 | int index = 0; 127 | for (Class type : method.getParameterTypes()) { 128 | if (type.equals(clazz)) { 129 | return index; 130 | } 131 | index++; 132 | } 133 | return -1; 134 | } 135 | 136 | @Override 137 | public void validate(Method method, Class clazz) { 138 | int paramsCount = method.getParameterTypes().length; 139 | final int socketIOClientIndex = paramIndex(method, SocketIOClient.class); 140 | final int ackRequestIndex = paramIndex(method, AckRequest.class); 141 | List dataIndexes = dataIndexes(method); 142 | paramsCount -= dataIndexes.size(); 143 | if (socketIOClientIndex != -1) { 144 | paramsCount--; 145 | } 146 | if (ackRequestIndex != -1) { 147 | paramsCount--; 148 | } 149 | if (paramsCount != 0) { 150 | throw new IllegalArgumentException("Wrong OnEvent listener signature: " + clazz + "." + method.getName()); 151 | } 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/transport/NamespaceClient.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.transport; 17 | 18 | import java.net.SocketAddress; 19 | import java.util.Arrays; 20 | import java.util.Set; 21 | import java.util.UUID; 22 | import java.util.concurrent.atomic.AtomicBoolean; 23 | 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import com.corundumstudio.socketio.AckCallback; 28 | import com.corundumstudio.socketio.HandshakeData; 29 | import com.corundumstudio.socketio.SocketIOClient; 30 | import com.corundumstudio.socketio.Transport; 31 | import com.corundumstudio.socketio.handler.ClientHead; 32 | import com.corundumstudio.socketio.namespace.Namespace; 33 | import com.corundumstudio.socketio.protocol.Packet; 34 | import com.corundumstudio.socketio.protocol.PacketType; 35 | 36 | public class NamespaceClient implements SocketIOClient { 37 | 38 | private static final Logger log = LoggerFactory.getLogger(NamespaceClient.class); 39 | 40 | private final AtomicBoolean disconnected = new AtomicBoolean(); 41 | private final ClientHead baseClient; 42 | private final Namespace namespace; 43 | 44 | public NamespaceClient(ClientHead baseClient, Namespace namespace) { 45 | this.baseClient = baseClient; 46 | this.namespace = namespace; 47 | namespace.addClient(this); 48 | } 49 | 50 | public ClientHead getBaseClient() { 51 | return baseClient; 52 | } 53 | 54 | @Override 55 | public Transport getTransport() { 56 | return baseClient.getCurrentTransport(); 57 | } 58 | 59 | @Override 60 | public boolean isChannelOpen() { 61 | return baseClient.isChannelOpen(); 62 | } 63 | 64 | @Override 65 | public Namespace getNamespace() { 66 | return namespace; 67 | } 68 | 69 | @Override 70 | public void sendEvent(String name, Object ... data) { 71 | Packet packet = new Packet(PacketType.MESSAGE); 72 | packet.setSubType(PacketType.EVENT); 73 | packet.setName(name); 74 | packet.setData(Arrays.asList(data)); 75 | send(packet); 76 | } 77 | 78 | @Override 79 | public void sendEvent(String name, AckCallback ackCallback, Object ... data) { 80 | Packet packet = new Packet(PacketType.MESSAGE); 81 | packet.setSubType(PacketType.EVENT); 82 | packet.setName(name); 83 | packet.setData(Arrays.asList(data)); 84 | send(packet, ackCallback); 85 | } 86 | 87 | private boolean isConnected() { 88 | return !disconnected.get() && baseClient.isConnected(); 89 | } 90 | 91 | @Override 92 | public void send(Packet packet, AckCallback ackCallback) { 93 | if (!isConnected()) { 94 | ackCallback.onTimeout(); 95 | return; 96 | } 97 | long index = baseClient.getAckManager().registerAck(getSessionId(), ackCallback); 98 | packet.setAckId(index); 99 | send(packet); 100 | } 101 | 102 | @Override 103 | public void send(Packet packet) { 104 | if (!isConnected()) { 105 | return; 106 | } 107 | packet.setNsp(namespace.getName()); 108 | baseClient.send(packet); 109 | } 110 | 111 | public void onDisconnect() { 112 | disconnected.set(true); 113 | 114 | baseClient.removeNamespaceClient(this); 115 | namespace.onDisconnect(this); 116 | 117 | log.debug("Client {} for namespace {} has been disconnected", baseClient.getSessionId(), getNamespace().getName()); 118 | } 119 | 120 | @Override 121 | public void disconnect() { 122 | Packet packet = new Packet(PacketType.MESSAGE); 123 | packet.setSubType(PacketType.DISCONNECT); 124 | send(packet); 125 | // onDisconnect(); 126 | } 127 | 128 | @Override 129 | public UUID getSessionId() { 130 | return baseClient.getSessionId(); 131 | } 132 | 133 | @Override 134 | public SocketAddress getRemoteAddress() { 135 | return baseClient.getRemoteAddress(); 136 | } 137 | 138 | @Override 139 | public int hashCode() { 140 | final int prime = 31; 141 | int result = 1; 142 | result = prime * result + ((getSessionId() == null) ? 0 : getSessionId().hashCode()); 143 | result = prime * result 144 | + ((getNamespace().getName() == null) ? 0 : getNamespace().getName().hashCode()); 145 | return result; 146 | } 147 | 148 | @Override 149 | public boolean equals(Object obj) { 150 | if (this == obj) 151 | return true; 152 | if (obj == null) 153 | return false; 154 | if (getClass() != obj.getClass()) 155 | return false; 156 | NamespaceClient other = (NamespaceClient) obj; 157 | if (getSessionId() == null) { 158 | if (other.getSessionId() != null) 159 | return false; 160 | } else if (!getSessionId().equals(other.getSessionId())) 161 | return false; 162 | if (getNamespace().getName() == null) { 163 | if (other.getNamespace().getName() != null) 164 | return false; 165 | } else if (!getNamespace().getName().equals(other.getNamespace().getName())) 166 | return false; 167 | return true; 168 | } 169 | 170 | @Override 171 | public void joinRoom(String room) { 172 | namespace.joinRoom(room, getSessionId()); 173 | } 174 | 175 | @Override 176 | public void leaveRoom(String room) { 177 | namespace.leaveRoom(room, getSessionId()); 178 | } 179 | 180 | @Override 181 | public void set(String key, Object val) { 182 | baseClient.getStore().set(key, val); 183 | } 184 | 185 | @Override 186 | public T get(String key) { 187 | return baseClient.getStore().get(key); 188 | } 189 | 190 | @Override 191 | public boolean has(String key) { 192 | return baseClient.getStore().has(key); 193 | } 194 | 195 | @Override 196 | public void del(String key) { 197 | baseClient.getStore().del(key); 198 | } 199 | 200 | @Override 201 | public Set getAllRooms() { 202 | return namespace.getRooms(this); 203 | } 204 | 205 | @Override 206 | public HandshakeData getHandshakeData() { 207 | return baseClient.getHandshakeData(); 208 | } 209 | 210 | } 211 | -------------------------------------------------------------------------------- /src/main/java/com/corundumstudio/socketio/ack/AckManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2012 Nikita Koksharov 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.corundumstudio.socketio.ack; 17 | 18 | import io.netty.util.internal.PlatformDependent; 19 | 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Set; 23 | import java.util.UUID; 24 | import java.util.concurrent.TimeUnit; 25 | import java.util.concurrent.atomic.AtomicLong; 26 | 27 | import org.slf4j.Logger; 28 | import org.slf4j.LoggerFactory; 29 | 30 | import com.corundumstudio.socketio.AckCallback; 31 | import com.corundumstudio.socketio.Disconnectable; 32 | import com.corundumstudio.socketio.MultiTypeAckCallback; 33 | import com.corundumstudio.socketio.MultiTypeArgs; 34 | import com.corundumstudio.socketio.SocketIOClient; 35 | import com.corundumstudio.socketio.handler.ClientHead; 36 | import com.corundumstudio.socketio.protocol.Packet; 37 | import com.corundumstudio.socketio.scheduler.CancelableScheduler; 38 | import com.corundumstudio.socketio.scheduler.SchedulerKey; 39 | import com.corundumstudio.socketio.scheduler.SchedulerKey.Type; 40 | 41 | public class AckManager implements Disconnectable { 42 | 43 | class AckEntry { 44 | 45 | final Map> ackCallbacks = PlatformDependent.newConcurrentHashMap(); 46 | final AtomicLong ackIndex = new AtomicLong(-1); 47 | 48 | public long addAckCallback(AckCallback callback) { 49 | long index = ackIndex.incrementAndGet(); 50 | ackCallbacks.put(index, callback); 51 | return index; 52 | } 53 | 54 | public Set getAckIndexes() { 55 | return ackCallbacks.keySet(); 56 | } 57 | 58 | public AckCallback getAckCallback(long index) { 59 | return ackCallbacks.get(index); 60 | } 61 | 62 | public AckCallback removeCallback(long index) { 63 | return ackCallbacks.remove(index); 64 | } 65 | 66 | public void initAckIndex(long index) { 67 | ackIndex.compareAndSet(-1, index); 68 | } 69 | 70 | } 71 | 72 | private static final Logger log = LoggerFactory.getLogger(AckManager.class); 73 | 74 | private final Map ackEntries = PlatformDependent.newConcurrentHashMap(); 75 | 76 | private final CancelableScheduler scheduler; 77 | 78 | public AckManager(CancelableScheduler scheduler) { 79 | super(); 80 | this.scheduler = scheduler; 81 | } 82 | 83 | public void initAckIndex(UUID sessionId, long index) { 84 | AckEntry ackEntry = getAckEntry(sessionId); 85 | ackEntry.initAckIndex(index); 86 | } 87 | 88 | private AckEntry getAckEntry(UUID sessionId) { 89 | AckEntry ackEntry = ackEntries.get(sessionId); 90 | if (ackEntry == null) { 91 | ackEntry = new AckEntry(); 92 | AckEntry oldAckEntry = ackEntries.put(sessionId, ackEntry); 93 | if (oldAckEntry != null) { 94 | ackEntry = oldAckEntry; 95 | } 96 | } 97 | return ackEntry; 98 | } 99 | 100 | @SuppressWarnings("unchecked") 101 | public void onAck(SocketIOClient client, Packet packet) { 102 | AckSchedulerKey key = new AckSchedulerKey(Type.ACK_TIMEOUT, client.getSessionId(), packet.getAckId()); 103 | scheduler.cancel(key); 104 | 105 | AckCallback callback = removeCallback(client.getSessionId(), packet.getAckId()); 106 | if (callback == null) { 107 | return; 108 | } 109 | if (callback instanceof MultiTypeAckCallback) { 110 | callback.onSuccess(new MultiTypeArgs(packet.>getData())); 111 | } else { 112 | Object param = null; 113 | List args = packet.getData(); 114 | if (!args.isEmpty()) { 115 | param = args.get(0); 116 | } 117 | if (args.size() > 1) { 118 | log.error("Wrong ack args amount. Should be only one argument, but current amount is: {}. Ack id: {}, sessionId: {}", 119 | args.size(), packet.getAckId(), client.getSessionId()); 120 | } 121 | callback.onSuccess(param); 122 | } 123 | } 124 | 125 | private AckCallback removeCallback(UUID sessionId, long index) { 126 | AckEntry ackEntry = ackEntries.get(sessionId); 127 | // may be null if client disconnected 128 | // before timeout occurs 129 | if (ackEntry != null) { 130 | return ackEntry.removeCallback(index); 131 | } 132 | return null; 133 | } 134 | 135 | public AckCallback getCallback(UUID sessionId, long index) { 136 | AckEntry ackEntry = getAckEntry(sessionId); 137 | return ackEntry.getAckCallback(index); 138 | } 139 | 140 | public long registerAck(UUID sessionId, AckCallback callback) { 141 | AckEntry ackEntry = getAckEntry(sessionId); 142 | ackEntry.initAckIndex(0); 143 | long index = ackEntry.addAckCallback(callback); 144 | 145 | if (log.isDebugEnabled()) { 146 | log.debug("AckCallback registered with id: {} for client: {}", index, sessionId); 147 | } 148 | 149 | scheduleTimeout(index, sessionId, callback); 150 | 151 | return index; 152 | } 153 | 154 | private void scheduleTimeout(final long index, final UUID sessionId, AckCallback callback) { 155 | if (callback.getTimeout() == -1) { 156 | return; 157 | } 158 | SchedulerKey key = new AckSchedulerKey(Type.ACK_TIMEOUT, sessionId, index); 159 | scheduler.scheduleCallback(key, new Runnable() { 160 | @Override 161 | public void run() { 162 | AckCallback cb = removeCallback(sessionId, index); 163 | if (cb != null) { 164 | cb.onTimeout(); 165 | } 166 | } 167 | }, callback.getTimeout(), TimeUnit.SECONDS); 168 | } 169 | 170 | @Override 171 | public void onDisconnect(ClientHead client) { 172 | AckEntry e = ackEntries.remove(client.getSessionId()); 173 | if (e == null) { 174 | return; 175 | } 176 | 177 | Set indexes = e.getAckIndexes(); 178 | for (Long index : indexes) { 179 | AckCallback callback = e.getAckCallback(index); 180 | if (callback != null) { 181 | callback.onTimeout(); 182 | } 183 | SchedulerKey key = new AckSchedulerKey(Type.ACK_TIMEOUT, client.getSessionId(), index); 184 | scheduler.cancel(key); 185 | } 186 | } 187 | 188 | } 189 | --------------------------------------------------------------------------------