Git Product home page Git Product logo

simplewebtransport's Introduction

Discord release openupm

Simple Web Transport

Low level Websocket Transport use by Mirror and Mirage

This Transport uses the websocket protocol. This allows this transport to be used in WebGL builds of unity.

Includes a Websocket server, standalone client, and a WebGL client so that both your Server and Client can be build with Unity.

Download

UnityPackage

  1. Download the code from the source folder or package on Release page.
  2. Put the code somewhere in your Assets folder

openUPM

  1. Add openupm registry. Click on the menu Edit -> Project settings..., and add a scoped registry like so:
    Name: OpenUPM
    Url: https://package.openupm.com
    Scopes:
    • com.james-frowen
  2. Close the project settings
  3. Open the package manager.
  4. Click on menu Window -> Package Manager and select "Packages: My Registries",
  5. select the latest version of SimpleWebTransport and click install, like so:
  6. You may come back to the package manager to unistall SimpleWebTransport or upgrade it.

Or add to Packages/manifest.json

{
    "dependencies": {
        "com.james-frowen.simplewebtransport": "2.2.0"
    },
    "scopedRegistries": [
        {
            "name": "package.openupm.com",
            "url": "https://package.openupm.com",
            "scopes": [
                "com.james-frowen.simplewebtransport"
            ]
        }
    ]
}

Usage

Below are some examples of how to set up a server and client so that they will connect and low any message sent between them

Server

// create server instance
var tcpConfig = new TcpConfig(noDelay: false, sendTimeout: 5000, receiveTimeout: 20000);
var server = new SimpleWebServer(5000, tcpConfig, ushort.MaxValue, 5000, new SslConfig());

// listen for events
server.onConnect += (id) => Debug.Log($"New Client connected, id:{id}");
server.onDisconnect += (id) => Debug.Log($"Client disconnected, id:{id}");
server.onData += (id, data) => Debug.Log($"Data from Client, id:{id}, {BitConverter.ToString(data.Array, data.Offset, data.Count)})");
server.onError += (id, exception) => Debug.Log($"Error because of Client, id:{id}, Error:{exception}");

// start server listening on port 7777
server.Start(7777);

// call Process to cause events to be invoked
// Call this from inside Unity Update method so that it will process message each frame
server.ProcessMessageQueue();

Client

// create client instance
// call static SimpleWebClient.Create method so that the correct client for WebGL or standalone is created
var tcpConfig = new TcpConfig(noDelay: false, sendTimeout: 5000, receiveTimeout: 20000);
var client = SimpleWebClient.Create(ushort.MaxValue, 5000, tcpConfig);

// listen for events
client.onConnect += () => Debug.Log($"Connected to Server");
client.onDisconnect += () => Debug.Log($"Disconnected from Server");
client.onData += (data) => Debug.Log($"Data from Server, {BitConverter.ToString(data.Array, data.Offset, data.Count)})");
client.onError += (exception) => Debug.Log($"Error because of Server, Error:{exception}");

// create url and connect to server
var builder = new UriBuilder
{
    Scheme = "ws",
    Host = "www.example.com",
    Port = 7777
};

client.Connect(builder.Uri);

// call Process to cause events to be invoked
// Call this from inside Unity Update method so that it will process message each frame
client.ProcessMessageQueue();

Send message to Server

Once the client is connected (after the onConnect event or check ConnectionState.) message can be sent

byte[] message = Encoding.ASCII.GetBytes("Hello Server");
client.Send(new ArraySegment<byte>(message));

Most of the time you will want to create a message Id so that the server can know what the message should be. But for this example we just send a string, if using the server example above it will log the bytes from the message when it is received

Bugs?

Please report any bugs or issues Here

Websocket Secure

This transport supports the wss protocol which is required for https pages.

Reverse proxy

Using a reverse proxy for SSL is generally more efficient than implementing SSL directly within Unity or other game servers, as the proxy can specialize in handling encryption, freeing up the game server to focus on delivering smooth gameplay.

To use reverse proxy with Mirror see this page Mirror/README.md

Nginx

Nginx is a popular reverse proxy thaat is easy to set up, and also has the ability to host WebGL files making it easy to set up development server. For a short guide on Nginx see this page: NginxConfig

Other reverse proxies

The Mirror docs explains how to set up some othher revierse proxies,

(not recommended) How to create and setup an SSL Cert

If you host your webgl build on a https domain you will need to use wss which will require a ssl cert.

See this page

Logging and Debugging

Logging is disabled by default to increase performance.

Log levels can be set by using Log.level = Log.Levels.warn.

Log methods

Log methods in this transport use the ConditionalAttribute so they are removed depending on the preprocessor defines.

These preprocessor defines effect the logging

  • DEBUG allows warn/error logs
  • SIMPLEWEB_LOG_ENABLED allows all logs

Without SIMPLEWEB_LOG_ENABLED info or verbose logging will never happen even if log level allows it.

See the Unity docs on how set custom defines.

simplewebtransport's People

Contributors

anthone avatar imerr avatar james-frowen avatar laur3nt1u avatar paradoks-studio avatar semantic-release-bot 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simplewebtransport's Issues

WebGL

Hello,

is this supposed/meant to work with WEBGL?

Messages larger than 65535 bytes

Any idea how to solve this limitation?
Normally this is fine, however, in our use case, we send a lot of game data at the start when a client connects since we stream pretty much the entire game's content, much of which is in the Megabytes of size.

Change the SendAll method parameter to take a ICollection<int> instead of List<int>

From the source, it doesn't seem there would be any detriment to changing this and would allow arrays and dict keys to be used directly.

public void SendAll(ICollection<int> connectionIds, ArraySegment<byte> source)
        {
            ArrayBuffer buffer = bufferPool.Take(source.Count);
            buffer.CopyFrom(source);
            buffer.SetReleasesRequired(connectionIds.Count);

            // make copy of array before for each, data sent to each client is the same
            foreach (int id in connectionIds)
                server.Send(id, buffer);
        }

Example is not working correctly due to encoding

Hi there!

I just noticed that the example that you give in the README is not working. You can test with those lines

byte[] message2 = Encoding.ASCII.GetBytes("Hello Server");
var test = new ArraySegment<byte>(message2);
string result = BitConverter.ToString(test.Array, test.Offset, test.Count);

the result variable has the following value 48-65-6C-6C-6F-20-53-65-72-76-65-72

doc: Rename+mv "ClientUseDefaultPort"

At first glance, this looks undesirable (and confusing). However, after looking at the tooltip, one with a reverse proxy may realize that nothing works because this isn't checked :)

This is such an overwhelmingly important feature that it can easily be overlooked in its current name.

Instead of this name and location under port, it should probably go right underr "Server Settings" 'at top and center.

The rename is debatable, but should probably be something similar to ReverseProxy. An explicit tooltip example mentioning "Nginx" may turn some heads to importance, as well. Heck ,it could be ReverseProxyUseDefaultPort if it's truly believed "default port" keyword would help folks (to me, it meant "ignore the port I listed above").

Connecting a client to subpaths

This may be more of a feature request than an issue. We want to host our game servers behind reverse proxies that rewrite the path, so that multiple servers can be hosted under the same domain under different paths. So for example, a game server URI could look like:

wss://xxx:123/ws/game-server/gs-c6431288-dd78-47a4-909a-cb085c416ea6

From what I saw, the C# UriBuilder supports a Path argument, but SimpleWebTransport does not use/expose it (we can only set hostname and port), so we can only connect the client to servers hosted at the root path of the domain.

Would that be something that can be added?

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.