### Example Servlet for Socket.IO
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Demonstrates how to create a Java servlet to handle incoming HTTP connections for Socket.IO. It initializes EngineIoServer and SocketIoServer and routes requests to the EngineIoServer.
```java
@WebServlet("/socket.io/*")
public class SocketIoServlet extends HttpServlet {
private final EngineIoServer mEngineIoServer = new EngineIoServer();
private final SocketIoServer mSocketIoServer = new SocketIoServer(mEngineIoServer);
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
mEngineIoServer.handleRequest(request, response);
}
}
```
--------------------------------
### Create Namespace
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Shows how to create or retrieve a Socket.IO namespace using the SocketIoServer instance. Namespaces allow for organizing communication channels.
```java
SocketIoNamespace namespace = server.namespace("/");
// Do something with namespace
```
--------------------------------
### Send Message to Client
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Provides an example of sending an event and data to a connected client using the send method on a SocketIoSocket. This allows for pushing information from the server to the client.
```java
// Sending event 'foo' with args 'bar arg', 1
socket.send("foo", "bar arg", 1);
```
--------------------------------
### Project Setup and Configuration
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/layout.html
This section details the initial setup for the socket.io-server-java project, including dependencies and basic configuration parameters. It outlines how to include the library in your project and set up the server instance.
```java
import io.socket.engine.EngineIO; // Example import
// Server configuration example
Configuration config = new Configuration();
config.setPort(3000);
// Server initialization
EngineIO server = new EngineIO(config);
server.start();
```
--------------------------------
### Broadcast Message to Room
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Shows how to broadcast an event and data to all clients within a specific room using the broadcast method on a SocketIoNamespace. This is useful for group messaging.
```java
// Broadcasting event 'foo' with args 'bar arg' to room 'room'
namespace.broadcast("room", "foo", "bar arg");
```
--------------------------------
### Listen for Client Messages
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Demonstrates how to attach an event listener to a SocketIoSocket to receive messages from a client. The listener can process any arguments sent by the client.
```java
// Attaching to 'foo' event
socket.on("foo", new Emitter.Listener() {
@Override
public void call(Object... args) {
// Arugments from client available in 'args'
}
});
```
--------------------------------
### Listen for Connections
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/using.rst
Illustrates how to attach a listener to the 'connection' event on a SocketIoNamespace to detect and handle new client connections. The connected socket is provided as an argument.
```java
namespace.on("connection", new Emitter.Listener() {
@Override
public void call(Object... args) {
SocketIoSocket socket = (SocketIoSocket) args[0];
// Do something with socket
}
});
```
--------------------------------
### Gradle Dependency for Socket.IO Java Server
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/install.rst
Add this line to your build.gradle file to include the Socket.IO Java Server Library in your Gradle project. The current version is 4.0.1.
```gradle
compile ('io.socket:socket.io-server:4.0.1')
```
--------------------------------
### Maven Dependency for Socket.IO Java Server
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/install.rst
Add this dependency to your pom.xml file to include the Socket.IO Java Server Library in your Maven project. The current version is 4.0.1.
```xml
io.socket
socket.io-server
4.0.1
```
--------------------------------
### Search Functionality Initialization
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/search.html
Initializes the search functionality by loading the search index using jQuery. This script is typically executed when the page loads.
```javascript
jQuery(function() {
Search.loadIndex("{{ pathto('searchindex.js', 1) }}");
});
```
--------------------------------
### Sphinx Configuration and Navigation
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/breadcrumbs.html
This snippet details Sphinx configuration for handling source file suffixes and displaying version control links (GitHub, Bitbucket, GitLab). It also manages the display of previous and next page navigation buttons.
```html
{# Support for Sphinx 1.3+ page_source_suffix, but don't break old builds. #} {% if page_source_suffix %} {% set suffix = page_source_suffix %} {% else %} {% set suffix = source_suffix %} {% endif %} {% if meta is defined and meta is not none %} {% set check_meta = True %} {% else %} {% set check_meta = False %} {% endif %} {% if check_meta and 'github_url' in meta %} {% set display_github = True %} {% endif %} {% if check_meta and 'bitbucket_url' in meta %} {% set display_bitbucket = True %} {% endif %} {% if check_meta and 'gitlab_url' in meta %} {% set display_gitlab = True %} {% endif %}
{% block breadcrumbs %}* [{{ _('Docs') }}]({{ pathto(master_doc) }}) »
{% for doc in parents %}* [{{ doc.title }}]({{ doc.link|e }}) »
{% endfor %}* {{ title }}
{% endblock %} {% block breadcrumbs_aside %}* {% if hasdoc(pagename) %} {% if display_github %} {% if check_meta and 'github_url' in meta %} [{{ _('Edit on GitHub') }}]({{ meta['github_url'] }}) {% else %} [{{ _('Edit on GitHub') }}](https://{{ github_host|default() {% endif %} {% elif display_bitbucket %} {% if check_meta and 'bitbucket_url' in meta %} [{{ _('Edit on Bitbucket') }}]({{ meta['bitbucket_url'] }}) {% else %} [{{ _('Edit on Bitbucket') }}](https://bitbucket.org/{{ bitbucket_user }}/{{ bitbucket_repo }}/src/{{ bitbucket_version}}{{ conf_py_path }}{{ pagename }}{{ suffix }}?mode={{ theme_vcs_pageview_mode|default() {% endif %} {% elif display_gitlab %} {% if check_meta and 'gitlab_url' in meta %} [{{ _('Edit on GitLab') }}]({{ meta['gitlab_url'] }}) {% else %} [{{ _('Edit on GitLab') }}](https://{{ gitlab_host|default() {% endif %} {% elif show_source and source_url_prefix %} [{{ _('View page source') }}]({{ source_url_prefix }}{{ pagename }}{{ suffix }}) {% elif show_source and has_source and sourcename %} [{{ _('View page source') }}]({{ pathto('_sources/' + sourcename, true)|e }}) {% endif %} {% endif %}
{% endblock %}
{% if (theme_prev_next_buttons_location == 'top' or theme_prev_next_buttons_location == 'both') and (next or prev) %}
{% if next %} [Next]({{ next.link|e }} "{{ next.title|striptags|e }}") {% endif %} {% if prev %} [Previous]({{ prev.link|e }} "{{ prev.title|striptags|e }}") {% endif %}
{% endif %}
* * *
```
--------------------------------
### Search Page Template
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/search.html
This HTML template is used for the search page of the socket.io-server-java project. It includes logic for loading the search index and displaying search results.
```html
{# basic/search.html ~~~~~~~~~~~~~~~~~ Template for the search page. :copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. #} {%- extends "layout.html" %} {% set title = \_('Search') %} {% set script\_files = script\_files + [\'\_static/searchtools.js\'] %} {% block footer %} jQuery(function() { Search.loadIndex("{{ pathto('searchindex.js', 1) }}"); }); {# this is used when loading the search index using $.ajax fails, such as on Chrome for documents on localhost #} {{ super() }} {% endblock %} {% block body %}
{% trans %}Please activate JavaScript to enable the search functionality.{% endtrans %}
{% if search\_performed %}
{{ \_('Search Results') }}
--------------------------
{% if not search\_results %}
{{ \_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.') }}
{% endif %} {% endif %}
{% if search\_results %}
{% for href, caption, context in search\_results %}* [{{ caption }}]({{ pathto(item.href) }})
{{ context|e }}
{% endfor %}
{% endif %}
{% endblock %}
```
--------------------------------
### API Documentation - Core Server Functionality
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/layout.html
Provides an overview of the core API methods available in the socket.io-server-java library for managing the server lifecycle, client connections, and event handling.
```APIDOC
EngineIO:
__init__(configuration: Configuration)
Initializes the Socket.IO server with the given configuration.
Parameters:
configuration: An instance of Configuration containing server settings.
start():
Starts the Socket.IO server, making it listen for incoming connections.
stop():
Stops the Socket.IO server gracefully.
on(event: String, listener: Consumer | Runnable):
Registers a listener for a specific event (e.g., 'connection', 'disconnect').
Parameters:
event: The name of the event to listen for.
listener: A callback function to execute when the event occurs.
getEmitter(): Emitter
Returns an Emitter instance for broadcasting messages.
Client:
getId(): String
Returns the unique identifier for the client connection.
send(data: Object):
Sends data to the specific client.
disconnect():
Disconnects the specific client.
Configuration:
setPort(port: int):
Sets the port number for the server to listen on.
getPort(): int
Gets the current port number.
// Other configuration options like transports, pingInterval, etc.
```
--------------------------------
### Socket.IO Java Server API Documentation
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/index.rst
This section provides API documentation for the Socket.IO Java Server, detailing its classes, methods, and usage patterns for real-time communication.
```apidoc
SocketIOServer:
__init__(Configuration configuration)
Initializes the Socket.IO server with a given configuration.
Parameters:
configuration: The configuration object for the server.
start()
Starts the Socket.IO server and begins listening for connections.
stop()
Stops the Socket.IO server and releases resources.
addNamespace(String namespace, BiConsumer handler)
Adds a custom namespace to the server.
Parameters:
namespace: The name of the namespace.
handler: A handler for incoming data packets on this namespace.
addEventListener(String eventName, Class dataClass, BiConsumer handler)
Adds a listener for a specific event.
Parameters:
eventName: The name of the event to listen for.
dataClass: The class of the data expected for this event.
handler: A handler for the event, receiving the client and the deserialized data.
sendEvent(String namespace, SocketIOClient client, String eventName, Object data)
Sends an event to a specific client within a namespace.
Parameters:
namespace: The namespace for the event.
client: The target client.
eventName: The name of the event to send.
data: The data payload for the event.
Configuration:
host: The hostname or IP address to bind to.
port: The port number to listen on.
bossThreads: Number of boss threads for the Netty server.
workerThreads: Number of worker threads for the Netty server.
pingInterval: Interval in milliseconds for sending ping frames.
pingTimeout: Timeout in milliseconds for receiving pong frames.
upgradeTimeout: Timeout in milliseconds for the upgrade process.
maxHttpContentLength: Maximum length of HTTP content.
allowHeaders: List of allowed HTTP headers.
allowOrigins: List of allowed origins (CORS).
DataPacket:
event: The name of the event.
data: The data payload, typically a List of Objects.
type: The type of packet (e.g., 'open', 'pong', 'message', 'upgrade', 'ping', 'close').
nsp: The namespace of the packet.
```
--------------------------------
### Handling Socket.IO Events
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/layout.html
Demonstrates how to handle incoming Socket.IO events, including connection, disconnection, and custom events. This is crucial for managing real-time interactions between clients and the server.
```java
server.on("connection", (client) -> {
System.out.println("Client connected: " + client.getId());
client.on("message", (data) -> {
System.out.println("Message from client: " + data);
client.send("Server received: " + data);
});
client.on("disconnect", () -> {
System.out.println("Client disconnected: " + client.getId());
});
});
```
--------------------------------
### SocketIoNamespace Methods and Events
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/api.rst
Represents a Socket.IO namespace instance, with methods for broadcasting and events for client connections.
```APIDOC
SocketIoNamespace:
broadcast(event: String, data: Object, rooms: Set = null):
Broadcasts an event to one or many rooms.
Events:
connect(socket: SocketIoSocket):
Emitted when a new client connection is established.
connection(socket: SocketIoSocket):
Alias for the 'connect' event.
```
--------------------------------
### SocketIoServer Methods
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/api.rst
Provides methods for managing namespaces and handling Engine.IO connections within the Socket.IO server.
```APIDOC
SocketIoServer:
hasNamespace(namespace: String): boolean
Checks if a namespace is registered with the server.
namespace(namespace: String): SocketIoNamespace
Creates or retrieves a namespace instance.
namespace(provider: SocketIoNamespaceProvider): SocketIoNamespace
Creates a dynamic namespace using a SocketIoNamespaceProvider.
namespace(pattern: Pattern): SocketIoNamespace
Creates a dynamic namespace using a Pattern instance.
Note: Ensure the pattern accounts for the starting '/'.
```
--------------------------------
### Broadcasting Messages
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/_themes/sphinx_rtd_theme/layout.html
Illustrates how to broadcast messages to all connected clients or specific rooms. This functionality is essential for real-time updates and notifications across multiple clients.
```java
// Broadcast to all clients
server.getEmitter().emit("broadcast", "Hello everyone!");
// Broadcast to a specific room (assuming rooms are implemented)
// server.getRoom("room1").emit("update", "New update for room1");
```
--------------------------------
### Gradle Dependency for Socket.IO Server Java
Source: https://github.com/socketio/socket.io-server-java/blob/master/README.md
This snippet demonstrates how to include the Socket.IO Server Java library in a Gradle project's build.gradle file. It specifies the artifact and version for compilation.
```groovy
compile ('io.socket:socket.io-server:4.0.1')
```
--------------------------------
### Maven Dependency for Socket.IO Server Java
Source: https://github.com/socketio/socket.io-server-java/blob/master/README.md
This snippet shows how to add the Socket.IO Server Java library as a dependency in a Maven project's pom.xml file. It specifies the group ID, artifact ID, and version.
```xml
io.socket
socket.io-server
4.0.1
```
--------------------------------
### SocketIoSocket Methods and Events
Source: https://github.com/socketio/socket.io-server-java/blob/master/docs/api.rst
Represents a socket connected to a client, with methods for sending messages, managing rooms, and handling disconnections.
```APIDOC
SocketIoSocket:
send(event: String, data: Object, ack: Function = null):
Sends an event to the client with an optional acknowledge callback.
broadcast(event: String, data: Object, rooms: Set = null):
Broadcasts an event to all sockets in one or many rooms, excluding this socket.
disconnect():
Disconnects the socket.
joinRoom(room: String):
Adds this socket to a room.
joinRoom(rooms: Set):
Adds this socket to multiple rooms.
leaveRoom(room: String):
Removes this socket from a room.
leaveRoom(rooms: Set):
Removes this socket from multiple rooms.
leaveAllRooms():
Removes this socket from all rooms.
Events:
disconnecting():
Emitted before disconnecting from the client.
disconnect():
Emitted after disconnecting from the client.
error(reason: String):
Raised on error, with the reason for the error.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.