Coder Social home page Coder Social logo

xlui / websocketexample Goto Github PK

View Code? Open in Web Editor NEW
62.0 6.0 25.0 2.82 MB

Spring Boot WebSocket Server with Android client and browser client.

Home Page: https://xlui.me/t/spring-boot-websocket-android-client/

License: MIT License

Java 77.46% HTML 22.54%
websocket spring-boot stomp

websocketexample's Introduction

Spring Boot WebSocket And Android Client

Spring Boot WebSocket Server, with a browser client and a simple Android client. Android client uses StompProtocolAndroid which implements ptotocol STOMP on Android, to subscribe or send message to server.

Introduction

δΈ­ζ–‡

Server now include three endpoints to receive message from client:

  1. /broadcast

This endpoint will simply transfer all messages it received to subscriber of /b.

  1. /group/{groupID}

This endpoint is used to dynamicly create groups. For example, client can send a message to /group/1, and all subscriber of /g/1 will receive the message. Also, you can change the subscribe endpoint by changing the Controller and WebSocketConfig

  1. /chat

Endpoint /chat is used to enable point-to-point communication. If Alice(with userID 1) want to chat with Bob(with userID 2), she should send a message to endpoint /chat with a special json object defined as ChatMessage:

// js code
function sendMessage() {
    var message = $('#message').val();
    stompClient.send('/chat', {}, JSON.stringify({
        'userID': 2, 
        'fromUserID': 1, 
        'message': "Hello Bob"})
    );
}

userID is necessary, this field will be used in server code to transfer message:

simpMessagingTemplate.convertAndSendToUser(String.valueOf(chatMessage.getUserID()), "/msg", response);

Through code above, the message from Alice will be sent to /user/2/msg, and if Bob subscribe it(also means subscribe himself), he will receive the message.

And Alice should also subscribe herself to receive message sent to her:

stompClient.subscribe('/user/' + 1 + '/msg', function (response) {
    showResponse(JSON.parse(response.body).responseMessage);
});

So when Bob send a message to Alice, she will receive it correctly.

Token-Authorization

Sometimes, we want our endpoint can only be accessed by authorized users. So we need check users' identify.

And I have add an example of passing token through HTTP headers.

For server, we need to receive the header in our endpoint controller method:

private String token = "this is a token generated by your code!";

@MessageMapping("/broadcast")
@SendTo("/b")
public Response say(Message message, @Header(value = "authorization") String authorizationToken) {
    if (authorizationToken.equals(token)) {
        System.out.println("Token check success!!!");
    } else {
        System.out.println("Token check failed!!!");
    }
    return new Response("Welcome, " + message.getName() + "!");
}

When you send a HTTP header authorization with a STOMP SEND method, the authorization token will be received properly.

For browser client, what we should do is add HTTP header in out SEND method:

stompClient.send(
    '/broadcast',
    {
        "authorization": "this is a token generated by your code!"
    },
    JSON.stringify({'name': name})
);

So when we send a message to endpoint /broadcast, the header authorization will be sent as well. And the server will do some check to the authorizationToken.

For android client, it is similar to the browser client:

String token = "this is a token generated by your code!";
StompHeader authorizationHeader = new StompHeader("authorization", token);
stompClient.send(new StompMessage(
        // Stomp command
        StompCommand.SEND,
        // Stomp Headers, Send Headers with STOMP
        // the first header is necessary, and the other can be customized by ourselves
        Arrays.asList(new StompHeader(StompHeader.DESTINATION, Const.broadcast), authorizationHeader),
        // Stomp payload
        jsonObject.toString())
    ).subscribe(...);

So, now we can generate token in server and send the token to users after the successful login. When user want to send message to endpoints we provide, a valid token is required!

Server

spring boot starter

Broadcast(Browser)

broadcast in browser

Broadcast(Android)

broadcast in android

Dynamic Groups(Browser)

group in browser

Dynamic Groups(Android)

group in android

Point-to-Point Chat(Browser)

chat in browser

Point-to-Point Chat(Android)

chat in browser

LICENSE

MIT

websocketexample's People

Contributors

xlui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

websocketexample's Issues

could not able connect with android

Hi Thanks for provide great example but i am getting these error in android client logs:
W/xlui.example.i: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
W/xlui.example.i: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xlui.example.i: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (light greylist, reflection)
Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (light greylist, reflection)
Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (light greylist, reflection)
D/StompClient: Connect
D/AbstractConnectionProvider: Emit lifecycle event: ERROR
D/StompClient: Socket closed with error
D/AbstractConnectionProvider: Emit lifecycle event: CLOSED
D/StompClient: Socket closed
D/StompClient: Stomp disconnected
I/xlui: Subscribe to the broadcast
I/Adreno: QUALCOMM build : cf57c9c, I1cb5c4d1cc
Build Date : 09/23/18
OpenGL ES Shader Compiler Version: EV031.25.03.01
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
Build Config : S L 6.0.7 AArch64
I/Adreno: PFP: 0x005ff112, ME: 0x005ff066
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 2
I/Toast: Show toast from OpPackageName:app.xlui.example.im, PackageName:app.xlui.example.im
I/xlui.example.i: ProcessProfilingInfo new_methods=0 is saved saved_to_disk=0 resolve_classes_delay=8000

please help me on this

Android Client Produces java.io.EOFException

Using okhttp WebSocket as a stomp client will throws an error after about 1 min of inactivity.

java.lang.Exception: java.io.EOFException

This is because that StompProtocolAndroid have not implement heart beat on creating connections, so we have to implement it by ourselves.

Here is an example:

// code to set a scheduled task, I'm sorry for ignoring this part, but I don't know how to do this.
stompClient.send("", "")subscribe();   // send a heart beat

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.