briandilley / jsonrpc4j

JSON-RPC for Java
MIT License
1.05k stars 438 forks source link

Usage with WebSockets #143

Open aabluedragon opened 8 years ago

aabluedragon commented 8 years ago

How can StreamServer be used with WebSockets?

The StreamServer constructor is: public StreamServer(JsonRpcBasicServer jsonRpcServer, int maxThreads, ServerSocket serverSocket)

I might be missing something obvious here, but I've found no other way to utilise this constructor for WebSockets, other than running a WebSockets --> TCP proxy in the background.

martintreurnicht commented 7 years ago

So i'm not sure how your using this, i'm using this with spring's websocket framework. It actually doesn't really matter at the end of the day, as long as you can provide it with a input and output stream you're good. Here is how i did it:

ObjectMapper mapper = new ObjectMapper()
Object handler = null; // This would be an instance of a class annotated with @JsonRpcService
JsonRpcBasicServer server = JsonRpcBasicServer(mapper, handler)

Then it's simply a case of having the following code in your handleMessage function:

public handleTextMessage(WebSocketSession session, TextMessage message) {
    OutputStream out = ByteArrayOutputStream()
        InputStream in = ByteArrayInputStream(message.asBytes())
    server.handleRequest(in, out)
    session.sendMessage(new TextMessage(out.toByteArray()))
}