Easy to use threaded socket communication in unity
Go to the Package Manager window, press the add button, and select "Add package from Git URL..."
Paste in this link: https://github.com/WeibelLab/Comms-Unity.git
You may get an error saying import failed. Paste in the link a second time.
Unity will then import the package and display a series of errors in the Console. Unity will automatically fix all of these, you can safely clear them.
You'll need a Server and a Client - these can be on the same or different computers. If they are on different computers, make sure unity is allowed through the firewall, and your system recognizes your network as a private network.
- Setup the server first
Choose a large port (1200-49000)
I recommend using dynamic messages. You might choose non-dynamic to marginally increase performance or if working with a custom client/server. - Setup the client
set thehost
to the IP address of your server's computer (127.0.0.1
if on the same computer) and theport
to whatever you set your server to listen on. - Run both your client and your server and see if you get a connection message
- Now make a script to send messages. Drag in the ReliableCommunication reference onto the component.
using Comms;
using UnityEngine;
public class SendMessage : MonoBehaviour
{
public ReliableCommunication comm;
private void Start() {
// Sending Strings
comm.Send("Hello");
// Sending JSON
// JSONObject json = new JSONObject();
// json.AddField("type", "foo");
// json.AddField("data", "bar");
// comm.Send(json);
}
}
- And a script to receive messages
using Comms;
using UnityEngine;
public class ReceiveMessage : MonoBehaviour
{
public ReliableCommunication comm;
public void OnMessage(string msg) {
Debug.Log("Client said: " + msg);
// Do something
}
}
To hook up the event listener,
- go into the "Data Events" tab
- select your message type (
string
for this example) - add an event
- connect to your script
Now when you run the server then client, your client will send a 'hello' message to the server which will log the message.
- Add connection/disconnection messages If you want to know when clients connect or disconnect:
- Add code that will run when the events happen (note that the methods receive a
ReliableCommunication
reference):
public void OnConnection(ReliableCommunication instance) {
Debug.Log(instance.name + " connected");
}
public void OnDisconnection(ReliableCommunication instance) {
Debug.Log(instance.name + " disconnected");
}