[Idea] Move Receive() to it's own Listen() method

Open
#39 3 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
38/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Stale
Tech stack
csharp, unity
Domain
networking

Research direction

Read Websocket.cs and its WebGL implementation first. Separate the Receive() call from Connect(), add the Listen() method and the WebGL compatibility method described in the issue, then verify that callers can await Connect() and start listening from the open handler without special WebGL handling.

Written by the indexing model from the issue text.

Description

Current Receive() is called at the end of Connect(). This means that if you ever want to await the Connect() call (so that you move on when it's connected), it won't actually return until the socket is disconnected. Moving it to it's own Listen() method would allow for that.

Something like:

// Websocket.cs
// 1) Remove the "await Receive()" call from the end of Connect()
// 2) Add an empty Listen() method in the WebGL implementation for compatibility
// 3) Add the following method:
public async void Listen()
{
	try
	{
		await Receive();
	}
	catch (Exception ex)
	{
		OnError?.Invoke(ex.Message);
		OnClose?.Invoke(WebSocketCloseCode.Abnormal);
	}
	finally
	{
		if (m_Socket != null)
		{
			m_TokenSource.Cancel();
			m_Socket.Dispose();
		}
	}
}

This lets you handle the websocket connection like so:

// WebsocketConnection.cs
public async Task ConnectAsync( string uri )
{
	if( this.isOpen )
	{
		Debug.LogWarning( "[WebSocketConnection] Trying to connect a websocket, but we're already open" );
		return; // we're already connected
	}

	// start our connection
	this.m_uri = uri;
	this.m_socket = new WebSocket( this.m_uri );
	
	// add our events
	this.m_socket.OnOpen += this._onWebSocketOpen;
	this.m_socket.OnClose += this._onWebSocketClose;
	this.m_socket.OnError += this._onWebSocketError;
	this.m_socket.OnMessage += this._onWebSocketMessage;

	Trace.Log( $"[WebSocketConnection] Opening a new connection to {this.m_uri}" );
	await this.m_socket.Connect();

	// wait until the socket is actually open
	await new WaitUntil( () => this.isOpen );
}

public void Update()
{
#if !UNITY_WEBGL || UNITY_EDITOR
	if( this.isOpen )
		this.m_socket.DispatchMessageQueue();
#endif
}

// called when our socket is open and ready for business
private void _onWebSocketOpen()
{
	Debug.Log( $"[WebSocketConnection] Connection to {this.m_uri} open!" );

	// start listening on the socket (NOTE: we're not awaiting here)
	this.m_socket.Listen();
}

Then actually using it in a method becomes much simpler. You can connect with something like:

public async void JoinGame()
{
	// check if we need to connect
	if( !this.m_websocketConnection.isConnected )
		await this.m_websocketConnection.ConnectAsync( this.m_websocketServerURI );

	this.m_websocketConnection.JoinGame();
}

As an added benefit, you don't need special handling for WebGL and nothing blocks unless it should

Dominant language
C#
Stars
1.7k
Forks
206
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from endel/NativeWebSocket

All issues in endel/NativeWebSocket

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.