Android websocket server java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Android Web socket with SSL server, SSL Client certificates, HTTP proxy

License

Foricher/Java-WebSocket-Android-SSL

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.markdown

This repository contains a barebones WebSocket server and client implementation written in 100% Java. The underlying classes are implemented java.nio , which allows for a non-blocking event-driven model (similar to the WebSocket API for web browsers).

Implemented WebSocket protocol versions are:

Here some more details about protocol versions/drafts.

##Build You can build using Ant or Maven but there is nothing against just putting the source path src/main/java on your applications buildpath.

will create the javadoc of this library at doc/ and build the library itself: dest/java_websocket.jar

The ant targets are: compile , jar , doc and clean

Maven is supported. More documentation in that is yet to come.

Note: If you’re on Windows, then replace the : (colon) in the classpath in the commands below with a ; (semicolon).

After you build the library you can start the chat server (a WebSocketServer subclass):

java -cp build/examples:dist/java_websocket.jar ChatServer

Now that the server is started, you need to connect some clients. Run the Java chat client (a WebSocketClient subclass):

java -cp build/examples:dist/java_websocket.jar ChatClient

The chat client is a simple Swing GUI application that allows you to send messages to all other connected clients, and receive messages from others in a text box.

In the example folder is also a simple HTML file chat client chat.html , which can be opened by any browser. If the browser natively supports the WebSocket API, then it’s implementation will be used, otherwise it will fall back to a Flash-based WebSocket Implementation.

Writing your own WebSocket Server

The org.java_websocket.server.WebSocketServer abstract class implements the server-side of the WebSocket Protocol. A WebSocket server by itself doesn’t do anything except establish socket connections though HTTP. After that it’s up to your subclass to add purpose.

Writing your own WebSocket Client

The org.java_websocket.server.WebSocketClient abstract class can connect to valid WebSocket servers. The constructor expects a valid ws:// URI to connect to. Important events onOpen , onClose , onMessage and onIOError get fired throughout the life of the WebSocketClient, and must be implemented in your subclass.

This library supports wss. To see how to use wss please take a look at the examples.

If you do not have a valid certificate in place then you will have to create a self signed one. Browsers will simply refuse the connection in case of a bad certificate and will not ask the user to accept it. So the first step will be to make a browser to accept your self signed certificate. ( https://bugzilla.mozilla.org/show_bug.cgi?id=594502 ).
If the websocket server url is wss://localhost:8000 visit the url https://localhost:8000 with your browser. The browser will recognize the handshake and allow you to accept the certificate. This technique is also demonstrated in this video.

The vm option -Djavax.net.debug=all can help to find out if there is a problem with the certificate.

It is currently not possible to accept ws and wss connections at the same time via the same websocket server instance.

For some reason firefox does not allow multible connections to the same wss server if the server uses a different port than the default port(443).

If you want to use wss on the android platfrom you should take a look at this.

I ( @Davidiusdadi ) would be glad if you would give some feedback whether wss is working fine for you or not.

Java-WebSocket is known to work with:

Other JRE implementations may work as well, but haven’t been tested.

Testing in Android Emulator

Please note Android Emulator has issues using IPv6 addresses . Executing any socket related code (like this library) inside it will address an error

java.net.SocketException: Bad address family

You have to manually disable IPv6 by calling

java.lang.System.setProperty("java.net.preferIPv6Addresses", "false"); java.lang.System.setProperty("java.net.preferIPv4Stack", "true");

somewhere in your project, before instantiating the WebSocketClient class. You can check if you are currently testing in the Android Emulator like this

if ("google_sdk".equals( Build.PRODUCT )) < // . disable IPv6 >

If you are looking for help using Java-WebSocket you might want to check out the #java-websocket IRC room on the FreeNode IRC network.

Everything found in this repo is licensed under an MIT license. See the LICENSE file for specifics.

About

Android Web socket with SSL server, SSL Client certificates, HTTP proxy

Источник

WebSockets on Android Made Easy

Photo of Mariusz Karwowski

After working for a while with WebSockets in our internal project I would like to share my thoughts and experience with you.

What was the problem?

In our application, we needed a solution for local communication between devices. While searching for a solution we had to take under account that one of the devices will need to work as a server. After quick research, we’ve found out the best option was Java WebSockets library. The main advantage is that it has the capability of handling both, a server and a client on the android device. The main implementation of these features required extending two classes: WebSocketClient and WebSocketServer, and overriding their functions. Rest of the logic comes with right message handling.

WebSocket Server

In order to implement sockets server, we need to implement base hook functions.

import org.java_websocket.WebSocket import org.java_websocket.handshake.ClientHandshake import org.java_websocket.server.WebSocketServer import java.net.InetSocketAddress class CustomWebSocketServer( port: Int? = null ) : WebSocketServer(InetSocketAddress(port ?: PORT)) < override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) = Unit override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) = Unit override fun onMessage(conn: WebSocket?, message: String?) = Unit override fun onMessage(conn: WebSocket?, message: ByteBuffer?) = Unit override fun onStart() = Unit override fun onError(conn: WebSocket?, ex: Exception?) = Unit companion object < internal const val PORT = 50123 >> 

Because we are dealing with a cross-platform application we also need to override onMessage(conn: WebSocket?, message: ByteBuffer?) because iOS sends their messages as bytes. That’s the reason why we are be also sending our messages as bytes. If we need to keep devices connected to our server every single one goes through onOpen , just keep a reference to conn: WebSocket . Our project specification requires our server to communicate with all clients at a time so we won’t be needing specific references. The server is able to send broadcasts so it will come in handy.

Before we start implementing messages handling, keep in mind that if you want to keep reusing the same port you should add

In your init block. If you won’t add it, you either have to change your port with every launch or your server will sometimes have issues with starting on the same port.

To start the server you will have to call the start() method. This method will block the main thread. In our project, we are using RxJava to execute it on a background.

When it comes to messaging as I mentioned earlier to support the iOS we need to override second onMessage function as well:

override fun onMessage(conn: WebSocket?, message: ByteBuffer?)

Now, that we are able to also receive messages from iOS we can go into actually interacting with messages. Let’s add a high order function into constructor then:

class CustomWebSocketServer( port: Int? = null, private val onMessageReceived: (WebSocket?, String?) -> Unit ) : WebSocketServer(InetSocketAddress(port ?: PORT)) < … override fun onMessage(conn: WebSocket?, message: String?) < onMessageReceived(conn, message) >… > 

We will be back to our server in a second. It is time to do some work with the client.

WebSocket Client

import org.java_websocket.client.WebSocketClient import org.java_websocket.handshake.ServerHandshake import java.net.URI class CustomWebSocketClient( val address: String ) : WebSocketClient(URI(address))

As you can see on the server super constructor all we need to do is to pass InetSocketAddress with the given port in the client we have to pass URI with the address with given pattern “ws://$:$” . From here all you have to do is to call connect() from a background thread because just like a server it will block the main thread. And we will need to override onMessage(bytes: ByteBuffer?) to receive messages from iOS server.

class CustomWebSocketClient( address: String, private val onMessageReceived: (String?) -> Unit ) : WebSocketClient(URI(address)) < … override fun onMessage(message: String?) < onMessageReceived(message) >override fun onMessage(bytes: ByteBuffer?) < bytes ?: return val buffer = ByteArray(bytes.remaining()) bytes.get(buffer) onMessage(String(buffer, Charset.defaultCharset())) >… > 

Now that we have implemented client and server, it is finally time to send some messages.

Messaging

We have decided to handle the messages using the JSON format. To construct and manage our messages we can use the JSONObject type from the org.json package.

If we want to broadcast specific action from our server to notify all connected clients all we have to do is create a simple message and send it as follows:

val jsonObject = JSONObject().apply < put("notify", "remember to eat your vegetables") >server?.broadcast(jsonObject.toString().toByteArray(Charset.defaultCharset())) 

And from the client side, we can now display a received notification:

CustomWebSocketClient( address = "ws://192.160.0.98:50123", onMessageReceived = < message ->val jsonObject = JSONObject(message) if (jsonObject.has("notify")) < showSnackbar(jsonObject.getString("notify")) >> ) 

And that’s all you need to implement simple sockets-based server-client communication. You can now expand your implementation with some extra features like notifying about connectivity changes or adding client-server messaging.

As the pro tip, I would like to mention the biggest disadvantage of Java WebSockets is that when your server crashes you need to create a new instance. Fortunately, on a client-side, you can just call reconnect()

Final Worlds

WebSockets, come in handy when your application requires to maintain a persistent connection between your client’s application and server. As for our needs, we managed to handle changes in music playback as well as simply notifying the client app about certain events. Let us know if you are interested in building a client-server app. We are happy to help.

Photo of Mariusz Karwowski

More posts by this author

Источник

Читайте также:  User www data php
Оцените статью