-
Notifications
You must be signed in to change notification settings - Fork 2
Sending bytes
SimplSockets is responsible for sending packages consisting of an array of bytes. SimplSockets will not do any interpretation of these byte arrays, that is all up to the user. The library will append a message size and thread id, so the message will be processed in the correct thread and will have correct size.
The simplest way to send data is by sending a byte array
var arrayToSend = new byte[1000];
client.Send(arrayToSend);
This works nice & simple, and is relatively performant, because we do not need to wait for an answer. For many use cases, you should probably use this function.
However, if you are sending large messages with a high frequency, all these big objects will need to destroyed by the garbage collector, which can give significant delays. In this case you can also choose to rent memory blocks from a memorypool. This can give significant performance gains, but it makes the application responsible for returning the memory to the pool. If you forget to do this, memory usage may steadily increase until an out of memory exception occurs.
However, there is a problem here: when can you return the data to the pool? You won't want to release and loose the contents while it is still in the send queue. For this, there is the option ReturnAfterSend. This will instruct the SimplSocket to return the data to the pool only after the data has been sent and it is safe to clear the contents.
var arrayToSend = PooledMessage.Rent(1000);
client.Send(arrayToSend);
arrayToSend.ReturnAfterSend();
Sending a byte array from the server works similar to the client, with the difference that you should add the client you would like to send to:
// Wait until a new client has connected
var connectedClient = server.WaitForNewClient();
// Create a byte array to send
var arrayToSend = new byte[1000];
// Send it to the new client
server.Send(arrayToSend, connectedClient);
Sending to all clients can be done using broadcast.
server.Broadcast(arrayToSend);
Or, if you want you can do this manually
foreach (var connectedClient in server.ConnectedClients)
{
server.Send(arrayToSend, connectedClient);
}
It is also possible for a client to send a command and wait for a reply.
var receivedMessage = client.SendReceive(sendMessage);
in conjunction the server has a reply function to answer
server.Reply(answerMessage, receivedMessage);
Note that receivedMessage on both client and server side is a pooled message and needs to be returned to the pool when you are done.
These features are shown in more detail in this example and this example