【发布时间】:2018-07-23 17:50:26
【问题描述】:
我正在学习 Unity 中的网络。我对如何从客户端向服务器发送消息或事件感到困惑。我已经有了这些脚本,可以成功地将我的客户端连接到服务器。
这是我的服务器脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ServerNetwork : MonoBehaviour {
void Start()
{
SetupServer();
}
// Create a server and listen on a port
public void SetupServer()
{
NetworkServer.Listen(4444);
NetworkServer.RegisterHandler(MsgType.Connect, OnClientConnected);
Debug.Log("Server is running");
}
void OnClientConnected(NetworkMessage netMsg)
{
Debug.Log("Client connected");
Debug.Log(netMsg.msgType);
}
}
这是我的客户端脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class ClientNetwork : MonoBehaviour {
NetworkClient myClient;
public bool isClientConnected = false;
void Start()
{
SetupClient();
}
// 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);
isClientConnected = true;
}
// client function
public void OnConnected(NetworkMessage netMsg)
{
Debug.Log("Connected to server");
}
}
服务器脚本附加到 ServerScene 上的“NetworkManager”对象
客户端脚本附加到 ClientScene 上的“NetworkManager”对象
我已经单独构建了 ClientScene 作为客户端运行,并在编辑器中运行 ServerScene
使用这些脚本,我已经可以将客户端连接到服务器。从这里,我如何从客户端到服务器进行通信?
这里的目的是每秒从客户端向服务器发送实时分数。
谢谢
【问题讨论】:
标签: unity3d networking