用unity实现网络通信有很多种方法,比较大型的项目都是自定义通信协议,本文介绍unity自己封装的NetWork通信,一个简单的多人聊天室。
实验环境:unity5.2+VS2015+Win8
具体步骤:
1.启动unity新建工程,并创建脚本Server.cs 挂在一个空物体上,并且添加组件NetworkView。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Server : MonoBehaviour
{
private int port = 2000;
private int connectPort = 32;
public Text textMsg;
public Text connetcMsg;
void Start()
{
//创建服务器
NetworkConnectionError error = Network.InitializeServer(connectPort, port, false);
if (error == NetworkConnectionError.NoError)
{
connetcMsg.text = "服务器创建成功";
}
else
{
connetcMsg.text = error.ToString();
}
}
void Update()
{
for (int i = 0; i < Network.connections.Length; i++)
{
connetcMsg.text= Network.connections[i].ipAddress + "已连接!";
}
}
//当玩家断开时,清理断开玩家的遗留信息
void OnPlayerDisconnected(NetworkPlayer player)
{
connetcMsg.text = player.ipAddress + "断开连接!";
Network.RemoveRPCs(player);
Network.DestroyPlayerObjects(player);
}
//接收客户端的消息
[RPC]
void ReceiveMessage(string msg, NetworkMessageInfo info)
{
textMsg.text = info.sender.ipAddress + "玩家:" + msg;
}
}
2.创建新场景,并创建脚本Client.cs挂在一个空物体上,并且添加NetworkView。
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Client : MonoBehaviour
{
public Text textMsg;
public InputField inputMsg;
private string ip = "127.0.0.1";
private int port = 2000;
void Start()
{
//客户端连接服务器
NetworkConnectionError error = Network.Connect(ip, port);
if (error == NetworkConnectionError.NoError)
{
textMsg.text = "连接成功";
}
else
{
textMsg.text = error.ToString();
}
}
//客户端向服务器或者其他客户端发送消息
public void SelfSendMessage()
{
this.GetComponent<NetworkView>().RPC("ReceiveMessage", RPCMode.Others, inputMsg.text);
inputMsg.text = "";
}
//接收其他客户端的消息
[RPC]
void ReceiveMessage(string msg, NetworkMessageInfo info)
{
textMsg.text = info.sender.ipAddress + "玩家:" + msg;
}
}
3.Build 1个服务端程序和2个客户端程序,并注意勾选后台运行。
4.运行效果图。