Skip to content

Commit

Permalink
feat: adding versions of SendAll that accept ICollection or IEnumerable
Browse files Browse the repository at this point in the history
James-Frowen committed Apr 24, 2024
1 parent 5c0feaa commit 28b6b25
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions source/Runtime/Server/SimpleWebServer.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace JamesFrowen.SimpleWeb
@@ -38,6 +39,11 @@ public void Stop()
Active = false;
}

/// <summary>
/// Sends to a list of connections, use <see cref="List{int}"/> version to avoid foreach allocation
/// </summary>
/// <param name="connectionIds"></param>
/// <param name="source"></param>
public void SendAll(List<int> connectionIds, ArraySegment<byte> source)
{
ArrayBuffer buffer = bufferPool.Take(source.Count);
@@ -49,6 +55,38 @@ public void SendAll(List<int> connectionIds, ArraySegment<byte> source)
server.Send(id, buffer);
}

/// <summary>
/// Sends to a list of connections, use <see cref="ICollection{int}"/> version when you are using a non-list collection (will allocate in foreach)
/// </summary>
/// <param name="connectionIds"></param>
/// <param name="source"></param>
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);
}

/// <summary>
/// Sends to a list of connections, use <see cref="IEnumerable{int}"/> version in cases where you want to use LINQ to get connections (will allocate from LINQ functions and foreach)
/// </summary>
/// <param name="connectionIds"></param>
/// <param name="source"></param>
public void SendAll(IEnumerable<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);
}

public void SendOne(int connectionId, ArraySegment<byte> source)
{
ArrayBuffer buffer = bufferPool.Take(source.Count);

0 comments on commit 28b6b25

Please sign in to comment.