- Home /
Question by
dudaplx2 · Mar 07, 2018 at 08:05 AM ·
scripting problemnetworking
NetworkClient handler is not getting called.
Hello, I am trying to send and recieve messages beetween NetworkClients. I run two instances with the same code (editor and standalone). I can successfully register the handler (i can see it in "Handlers" while debugging), but "OnMessageRecieved" never gets called. I use "Network Manager HUD" for this.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
using UnityEngine.UI;
public class Streamer : NetworkManager
{
private short myTextMsg = 888;
NetworkWriter writer;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
if (client != null)
{
if (client.isConnected)
{
//writer = new NetworkWriter();
//writer.StartMessage(myTextMsg);
//writer.Write("Hello");
//writer.FinishMessage();
//client.SendWriter(writer, Channels.DefaultReliable);
client.Send(myTextMsg, new StringMessage("Hello"));
}
}
}
public override void OnClientConnect(NetworkConnection connection)
{
client.RegisterHandler(myTextMsg, OnMessageRecieved);
Debug.Log(client.connection.connectionId + " Connected!");
}
public void OnMessageRecieved(NetworkMessage netMsg)
{
Debug.Log("Message from " + netMsg.conn.hostId + ": " + netMsg.reader.ReadString());
}
}
Comment
Best Answer
Answer by dudaplx2 · Mar 07, 2018 at 11:17 AM
Ok, so it turns out, that NetworkClient.Send() sends data to the server and not the other client.
I had to add this (i stilll have to change SendToAll() to get what i want, but i'm out of time for today):
public override void OnStartServer()
{
base.OnStartServer();
NetworkServer.RegisterHandler(myTextMsg, OnServerMessageRecieved);
}
public void OnServerMessageRecieved(NetworkMessage netMsg)
{
NetworkServer.SendToAll(myTextMsg, netMsg.ReadMessage<TextMessage>());
}