Back to Documentation

Java SDK Examples

Real-world examples showing how to use the OddSockets Java SDK in production applications

View on GitHub
Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core SDK functionality.
import com.oddsockets.OddSockets;
import com.oddsockets.Channel;
import com.oddsockets.config.OddSocketsConfig;

public class BasicExample {
    public static void main(String[] args) {
        // Create configuration
        OddSocketsConfig config = new OddSocketsConfig.Builder()
            .apiKey("ak_live_1234567890abcdef")
            .build();

        // Initialize client
        OddSockets client = new OddSockets(config);

        // Get channel and subscribe
        Channel channel = client.channel("my-channel");
        channel.subscribe(message -> {
            System.out.println("Received: " + message.getData());
        });

        // Publish a message
        channel.publish("Hello, World!");
    }
}
Spring Boot Integration
Available
Complete Spring Boot application with auto-configuration, REST endpoints, and WebSocket integration.
@RestController
@RequestMapping("/api/chat")
public class ChatController {

    @Autowired
    private OddSockets oddSocketsClient;

    @PostMapping("/send")
    public ResponseEntity<String> sendMessage(@RequestBody ChatMessage message) {
        Channel channel = oddSocketsClient.channel("chat-room");
        
        try {
            channel.publish(message);
            return ResponseEntity.ok("Message sent successfully");
        } catch (Exception e) {
            return ResponseEntity.status(500)
                .body("Failed to send message");
        }
    }
}
Android Chat App
Available
Native Android chat application with real-time messaging, presence tracking, and offline support.
public class ChatActivity extends AppCompatActivity {
    private OddSockets oddSocketsClient;
    private Channel chatChannel;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        
        // Initialize OddSockets client
        OddSocketsConfig config = new OddSocketsConfig.Builder()
            .apiKey("ak_live_1234567890abcdef")
            .userId(getCurrentUserId())
            .build();
            
        oddSocketsClient = new OddSockets(config);
        chatChannel = oddSocketsClient.channel("mobile-chat");
        
        // Subscribe to messages
        chatChannel.subscribe(message -> {
            runOnUiThread(() -> displayMessage(message));
        });
    }
}
Kotlin Coroutines
Available
Modern Kotlin implementation using coroutines for async operations and structured concurrency.
import com.oddsockets.OddSockets
import com.oddsockets.config.OddSocketsConfig
import kotlinx.coroutines.*

class ChatService {
    private val oddSocketsClient: OddSockets
    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    init {
        val config = OddSocketsConfig.Builder()
            .apiKey("ak_live_1234567890abcdef")
            .userId("kotlin-user")
            .build()
            
        oddSocketsClient = OddSockets(config)
    }
    
    suspend fun publishMessage(channelName: String, message: Any) {
        val channel = oddSocketsClient.channel(channelName)
        
        try {
            val result = channel.publishAsync(message).await()
            println("Message published: ${result.messageId}")
        } catch (e: Exception) {
            println("Failed to publish: ${e.message}")
        }
    }
}
Micronaut Microservice
Available
Lightweight microservice built with Micronaut framework, featuring reactive streams and dependency injection.
@Controller("/api/chat")
public class ChatController {
    
    private final OddSockets oddSocketsClient;
    
    public ChatController(OddSockets oddSocketsClient) {
        this.oddSocketsClient = oddSocketsClient;
    }
    
    @Post("/send")
    public Single<HttpResponse<String>> sendMessage(@Body ChatMessage message) {
        Channel channel = oddSocketsClient.channel("micronaut-chat");
        
        return Single.fromFuture(channel.publishAsync(message))
            .map(result -> HttpResponse.ok("Message sent: " + result.getMessageId()))
            .onErrorReturn(throwable -> 
                HttpResponse.serverError("Failed: " + throwable.getMessage()));
    }
}
Quarkus Native
Available
High-performance Quarkus application with native compilation support and reactive programming model.
@Path("/api/chat")
@ApplicationScoped
public class ChatResource {
    
    @Inject
    OddSockets oddSocketsClient;
    
    @POST
    @Path("/send")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Uni<Response> sendMessage(ChatMessage message) {
        Channel channel = oddSocketsClient.channel("quarkus-chat");
        
        return Uni.createFrom().completionStage(channel.publishAsync(message))
            .map(result -> Response.ok()
                .entity(Map.of("messageId", result.getMessageId()))
                .build())
            .onFailure().recoverWithItem(throwable ->
                Response.serverError()
                    .entity(Map.of("error", throwable.getMessage()))
                    .build());
    }
}