- Home /
How to send simple values on local network?
Hi everyone,
I want to send a few values between two Unity 5.2 applications in a local network. All tutorials I found are about a complete multiplayer setup. All I want to do is updating two values (one Vector3 and one float) constantly from one application to the other one. There is no need for matchmaking, player spawning, and all that stuff. Even the IPs could be hardcoded. Is there any "slim" way to do this, or do I have to set up a complete multiplayer project just for my two values? Thanks in advance.
Comment
Best Answer
Answer by Quen · Oct 29, 2015 at 11:28 AM
After some more research, I was able to solve this by myself. Here is what I did, I think it is very slim and it works well:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class MyNetworkManager : MonoBehaviour
{
public bool isAtStartup = true;
NetworkClient myClient;
public const short MyDataMsgID = 815;
public bool isServer = false;
public bool isClient = false;
class MyMsgType
{
public static short ID = 815;
}
class MyDataMsg : MessageBase
{
public Vector3 position;
public float angle;
public string message;
}
void Update()
{
if (isAtStartup)
{
if (Input.GetKeyDown(KeyCode.Alpha1))
{
// Now this is the SERVER
SetupServer();
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
// Now this is the CLIENT
SetupClient();
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
// Now this is a SERVER and a Local CLIENT too
SetupServer();
SetupLocalClient();
}
}
else
{
if (isClient)
{
// Maybe add conditions on when to send message...
SendMyDataMessage();
}
}
}
// Create a server and listen on a port
public void SetupServer()
{
NetworkServer.Listen(4444);
NetworkServer.RegisterHandler(MyMsgType.ID, OnRecievingData);
isAtStartup = false;
isServer = true;
isClient = false;
}
// Create a client and connect to the server port
public void SetupClient()
{
myClient = new NetworkClient();
myClient.RegisterHandler(MsgType.Connect, OnConnected);
myClient.Connect("127.0.0.1", 4444);
isAtStartup = false;
isClient = true;
isServer = false;
}
// Create a local client and connect to the local server
public void SetupLocalClient()
{
myClient = ClientScene.ConnectLocalServer();
myClient.RegisterHandler(MsgType.Connect, OnConnected);
isAtStartup = false;
}
// What the CLIENT should do when connected
public void OnConnected(NetworkMessage netMsg)
{
Debug.Log("Connected to server");
}
// Call this with the CLIENT to send a message
public void SendMyDataMessage()
{
var msg = new MyDataMsg();
msg.position = new Vector3(0.0f,0.0f,0.0f);
msg.angle = -21.74f;
msg.message = "lets hope this comes through";
myClient.Send(MyMsgType.ID, msg);
}
// What the SERVCER should do when getting a message
public void OnRecievingData(NetworkMessage netMsg)
{
MyDataMsg myMsg = netMsg.ReadMessage<MyDataMsg>();
// use the values from the message here
Debug.Log("position: " + myMsg.position);
Debug.Log("angle: " + myMsg.angle);
Debug.Log("message: " + myMsg.message);
}
}