How to make simple chat system using Fish-Networking

Published at 8/20/2022, 11:45:30 AM

Hello

In this post, I will show you how to make a simple chat system using Fish-Networking.

A video explaining this post in detail will soon be available on my channel, so stay tuned.

So, to make it so all objects regardless of whether they're NetworkBehaviours or not can send messages, we will be utilizing a powerful feature of Fish-Networking called Broadcasts.

Broadcasts allow clients to send messages to the server and vice versa.

Broadcasts can be created by defining a struct (or preferably a readonly struct) and implementing the IBroadcast interface.

With that said, let's create a broadcast called SendMessageBroadcast like so:

public readonly struct SendMessageBroadcast : IBroadcast
{
    public readonly string Sender;
    public readonly string Message;
    
    public SendMessageBroadcast(string sender, string message)
    {
        Sender = sender;
        Message = message;
    }
}

As you can see, our broadcast is pretty simple. It has 2 properties, Sender and Message.

Now, let's go ahead and create a Chat component that will be responsible for handling incoming messages.

public sealed class Chat : NetworkBehaviour
{
    [SyncObject]
    public readonly SyncList<string> Messages = new SyncList<string>();
    
    public override void OnStartServer()
    {
        base.OnStartServer();
        
        ServerManager.RegisterBroadcast<SendMessageBroadcast>(SendMessageBroadcastHandler);
    }
    
    public override void OnStopServer()
    {
        base.OnStopServer();
        
        ServerManager.UnregisterBroadcast<SendMessageBroadcast>(SendMessageBroadcastHandler);
    }
    
    private void SendMessageBroadcastHandler(NetworkConnection networkConnection, SendMessageBroadcast broadcast)
    {
        Messages.Add($"{broadcast.Sender}: {broadcast.Message}");
    }
}

As you can see, our Chat component derives from NetworkBehaviour overrides the OnStartServer and OnStopServer methods. Inside them, we're registering and unregistering a server handler for the SendMessageBroadcast broadcast so that when a client sends a message, we can add it to our Messages sync list.

Now, to send a message, you can call ClientManager.Broadcast with the SendMessageBroadcast from anywhere like so:

InstanceFinder.ClientManager.Broadcast(new SendMessageBroadcast("Me", "Hello!"));

And, that's it!

Messages sent by clients will be added to our Messages sync list and will be accessible by any client connected to the server.

If you liked this post, consider supporting me on Ko-fi.

And, as mentioned before, stay tuned for a video explaining this post in detail on my channel.