I am trying to get a server to send a message to the client using the Unity Transport Layer.
The problem is that the client doesn’t seem to connect. I don’t get any errors.
Can someone please tell what the problem is and how to solve it?
These are the scripts:
Server
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class Server : MonoBehaviour
{
public int port = 6969;
int Reliable;
int UnReliable;
int HostID;
public int MaxConnections = 2;
public bool IsStarted = false;
private void Update()
{
if (IsStarted)
{
NetworkReceiver();
}
else
{
Network();
}
}
private void Network()
{
Debug.Log("Network is starting");
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
Reliable = cc.AddChannel(QosType.Reliable);
UnReliable = cc.AddChannel(QosType.Unreliable);
HostTopology Host = new HostTopology(cc, MaxConnections);
HostID = NetworkTransport.AddHost(Host, port, null);
Debug.Log("Network started");
IsStarted = true;
}
private void NetworkReceiver()
{
//Debug.Log("Network receiver");
if (IsStarted == false)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.ConnectEvent:
Debug.Log("has connected");
byte[] send = Encoding.ASCII.GetBytes("Hello World!");
NetworkTransport.Send(HostID, connectionId, Reliable, send, send.Length, out error);
break;
}
}
}
Client:
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
public class Client : MonoBehaviour
{
public int port = 6969;
public string ServerIp = "127.0.0.1";
int Reliable;
int UnReliable;
int HostID;
int ConnectionID;
public int MaxConnections = 2;
public bool IsStarted = false;
byte error;
private void Update()
{
if (IsStarted)
{
NetworkReceiver();
}
else
{
Network();
}
}
private void Network()
{
NetworkTransport.Init();
ConnectionConfig cc = new ConnectionConfig();
Reliable = cc.AddChannel(QosType.Reliable);
UnReliable = cc.AddChannel(QosType.Unreliable);
HostTopology Host = new HostTopology(cc, MaxConnections);
HostID = NetworkTransport.AddHost(Host, 0);
ConnectionID = NetworkTransport.Connect(HostID, ServerIp, port, 0, out error);
IsStarted = true;
}
private void NetworkReceiver()
{
Debug.Log("Network receiver");
if (IsStarted == false)
return;
int recHostId;
int connectionId;
int channelId;
byte[] recBuffer = new byte[1024];
int bufferSize = 1024;
int dataSize;
byte error;
NetworkEventType recData = NetworkTransport.Receive(out recHostId, out connectionId, out channelId, recBuffer, bufferSize, out dataSize, out error);
switch (recData)
{
case NetworkEventType.DataEvent:
GameObject.Find("Text").GetComponent<UnityEngine.UI.Text>().text = Encoding.ASCII.GetString(recBuffer);
Debug.Log("receiving data");
break;
}
}
}