Giter VIP home page Giter VIP logo

cn1-websockets's Introduction

Codename One WebSockets Library

This library adds WebSocket client support for Codename One apps.

Supported Platforms

  1. JavaSE (Codename One Simulator)

  2. Android

  3. iOS

  4. Javascript

  5. Windows (UWP)

Installation

For Maven Projects: To use this in a Codename One maven project, add the following dependency to your common/pom.xml dependencies section:

<dependency>
    <groupId>com.codenameone</groupId>
    <artifactId>websockets-lib</artifactId>
    <version>1.0</version>
    <type>pom</type>
</dependency>

For non-maven projects:

Copy the cn1-websockets.cn1lib file from the latest release into your project’s lib directory. Then select "Refresh Libs".

Chat Demo

Chat Demo

You can try this out by running the chat demo app.

The companion JavaEE server project for this demo app can be found here.

License

The MIT License (MIT)

Copyright (c) 2015 Steve Hannah

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sample Usage

final WebSocket sock = new WebSocket("ws://10.0.1.21:8080/WebSocketServer/whiteboardendpoint") {

    @Override
    protected void onOpen() {
        System.out.println("In onOpen");
    }

    @Override
    protected void onClose(int statusCode, String reason) {
        System.out.println("Connection closed");
    }

    @Override
    protected void onMessage(String message) {
        System.out.println("Received message "+message);
    }

    @Override
    protected void onError(Exception ex) {
        System.out.println("in onError");
    }

     @Override
     protected void onMessage(byte[] message) {
         // Received a binary message
     }

}
.autoReconnect(5000); // Automatically reconnect if connection fails or server disconnects
                      // Attempts every 5 seconds until successful
sock.connect();

Form hi = new Form("Hi World");
hi.addComponent(new Button(new Command("Ping Peer") {

     @Override
     public void actionPerformed(ActionEvent evt) {
         sock.send("Hello From Codename One");
     }
}));
hi.show();

Contributions

If you would like to build the source yourself, or make improvements, simply fork this project and build it locally.

Building From Source

$ git clone https://github.com/shannah/cn1-websockets.git
$ cd cn1-websockets-lib
$ mvn install

You should then be able to find the cn1-websockets.cn1lib in the common/target directory

Project Source Layout

The library project is contained in link:the cn1-websockets-lib[] directory. For details of project structure see The Codename One Maven Developers Guide.

Contact

cn1-websockets's People

Contributors

dependabot[bot] avatar shannah avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cn1-websockets's Issues

Simulator no longer connecting to WebSocket?

A few weeks ago I downloaded a zip of the demo. I modified the code to point to a local running WebSocket and had a chat working back and forth from an iOS debug build on my iPhone along with Javascript in a web browser. After updating my Codename One Eclipse plug-in, I am no longer able to connect to the WebSocket. The WebSocket itself appears to be perfectly fine since everything from the browser still works.

The sock.connect() call in the init() method of my Codename One project does not seem to be connecting properly. I am not entirely sure how to debug this native method. Is there anything I can try or possibly something that was changed that might caused this to stop working?

I even tried changing SERVER_URL to ws://translation.weblite.ca:8080/WebSocketDemo/chat, but it does not seem to be able to connect to that either anymore. All recent testing has been done using the Simulator.

close() method impl on Android noop

The close() method on the WebSocket seemed to do nothing (at least on Android).

When looking at the code, its actual implementation seems to be commented out. So right now there is no way to disconnect from a server unless the server itself disconnects you.

ClassNotFoundException WebSocketNativeImplImpl

I've imported the lib in to my Eclipse CN1 project as per the instructions and add the demo client code. But when i run i get the following:

java.lang.ClassNotFoundException: com.codename1.io.websocket.WebSocketNativeImplImpl

The class name should be WebSocketNativeImpl which i can find (ctrl + t) which is an interface. I can find that. So i copied it and created a WebSocketNativeImplImpl interface. Now i get:

java.lang.InstantiationException: com.codename1.io.websocket.WebSocketNativeImplImpl

important: crash on 64bit hardware

As Apple now requires 64-bit in App Store submissions, this issue is important.

FIX: change "int peer" to "long peer" (and related functions, too, and casts in .m code, too).

I would submit pull request, but I copy/pasted code into my codebase because I cannot use cn1 libs as is.

Add support for custom headers

Can you please add support for custom HTTP headers? Both Android and iOS (and probably others) seem to support it but I am not able to get it working.

public void addHeader(String key, String value);

[BUG] `autoreconnect` implementation is wrong

First of all, the following bug can be reproduced on Android and Simulator only. On iOS the autoreconnect doesn't work at all: if you turn off the Internet connection and then turn on it again, the WebSocket connection is not reopened on iOS, but on Android only. However, Android and Simulator have another issue, as described below.

For your convenience, to test my client code and to reproduce the bug, I keep my testing Spring Boot server (chat.mydissent.net) running for some days. On the server-side, there is a timer that send a WebSocket text message every second to the client with id "1234". It's only a test, I mostly copied that server code from the Codename One Academy, so I assume that it's correct.

Please try the following client code:

        String uniqueId = "1234";
        Form hi = new Form("WebSocket Test", BoxLayout.y());
        hi.show();

        final WebSocket sock = new WebSocket("wss://chat.mydissent.net/wsMsg") {
            @Override
            protected void onOpen() {
                Log.p("WebSocket onOpen - Sending uniqueId: " + uniqueId);
                hi.add("WebSocket onOpen - Sending uniqueId: " + uniqueId);
                hi.animateLayout(400);
                send(uniqueId);
            }

            @Override
            protected void onClose(int statusCode, String reason) {
                Log.p("WebSocket onClose");
                hi.add("WebSocket onClose");
                hi.animateLayout(400);
            }

            @Override
            protected void onMessage(String message) {
                Log.p("WebSocket onMessage: " + message);
                hi.add(new SpanLabel("WebSocket onMessage: " + message));
                hi.animateLayout(400);
            }

            @Override
            protected void onMessage(byte[] message) {
                Log.p("WebSocket onMessage (byte[]): " + message.toString());
            }

            @Override
            protected void onError(Exception ex) {
                Log.e(ex);
                hi.add(new SpanLabel("WebSocket onError:\n" + ex.getMessage()));
            }
        };
        sock.connect();
        sock.autoReconnect(5000);
        
        UITimer.timer(5000, false, hi, () -> {
            sock.close();
        });

The output is:

WebSocket

As you can see, after closing the WebSocket connection, autoReconnect reopened it. The expected behavior is that autoReconnect must reconnect only on network errors, and not when close is explicitly invoked.
The other excepted behaviour is that after turning off and then turning on the Internet connection, autoReconnect must work, but it's not so on iOS.

AbstractMethodError

Hi Steve.
I've installed library via cn1lib manager of my project and then refresh cn1lib.

When I launch my application on simulator, I obtain this message :
java.lang.AbstractMethodError: com.codename1.io.websocket.WebSocketNativeImplImpl.getReadyState()I About to start socket Sending connect at com.codename1.io.websocket.WebSocket.getReadyState(WebSocket.java:229) at com.codename1.io.websocket.WebSocket.connect(WebSocket.java:199) at com.amplitude.tablet.MainClass.showChat(MainClass.java:136) at com.amplitude.tablet.MainClass.start(MainClass.java:257) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at com.codename1.impl.javase.Executor$1$1.run(Executor.java:123) at com.codename1.ui.Display.processSerialCalls(Display.java:1154) at com.codename1.ui.Display.mainEDTLoop(Display.java:971) at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120) at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

It occurs when it invoked connect method of websocket.
(I'm using Eclipse).

Working with audio

I saw that you can send and receive data as byte[] -- would this be a good fit for working with audio to act as push-to-talk? I realize that there would be an issue with background services.

Would you recommend this for such a use case? Would it be too slow to process the audio?

Any related advice or pointers would be appreciated.

Thank you.

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.