NetWorkServer.cs
using UnityEngine;
using System.Collections; public class NetWorkServer : MonoBehaviour
{
// Use this for initialization
// 定义远程连接IP地址
private string remoteIP = "127.0.0.1";
// 定义远程的端口号
private int remotePort = ;
// 定义本地侦听的端口号
private int listenPort = ;
// 限制连接数量为15个用户
private int connectCount = ;
// 是否启用网络地址转换器
private bool useNAT = false; void OnGUI ()
{
switch (Network.peerType) {
case NetworkPeerType.Disconnected:
// 服务器未开启时,开启服务器
StartConnect ();
break;
case NetworkPeerType.Server:
// 成功连接服务器
OnServer ();
break;
case NetworkPeerType.Client:
break;
case NetworkPeerType.Connecting:
break;
}
} void StartConnect ()
{
remoteIP = GUI.TextField (new Rect (, , , ), remoteIP); if (GUI.Button (new Rect (, , , ), "创建服务器")) { Network.incomingPassword = "UnityNetwork";
NetworkConnectionError error = Network.InitializeServer (connectCount, remotePort, useNAT);
Debug.Log (error);
}
} void OnServer ()
{
GUILayout.Label (" 服务端创建成功。等待连接····"); // 得到的 IP 与端口
string ip = Network.player.ipAddress;
int port = Network.player.port;
GUILayout.Label (" ip地址:" + ip + ".\n 端口号码:" + port); // 连接到服务器的所有客户端
int connectLength = Network.connections.Length; // 遍历所有客户端并获取IP与端口号
for (int i = ; i < connectLength; i++) {
GUILayout.Label (" 连接的IP:" + Network.connections [i].ipAddress);
GUILayout.Label (" 连接的端口:" + Network.connections [i].port);
} if (GUI.Button (new Rect (, , , ), "断开连接")) {
// 从服务器上断开连接
Network.Disconnect ();
}
} void OnPlayerConnected (NetworkPlayer player)
{ GetComponent<NetworkView> ().RPC ("OnNetworkLoaded", RPCMode.Others, player); } void OnPlayerDisconnected (NetworkPlayer player)
{
Debug.Log ("清除对象: " + player);
Network.RemoveRPCs (player);
Network.DestroyPlayerObjects (player);
} }
NetWorkColient.cs
using UnityEngine;
using System.Collections; public class NetWorkColient : MonoBehaviour
{ // Use this for initialization
// 定义远程 IP 地址
private string remoteIP = "127.0.0.1";
// 定义侦听端口
private int listenPort = ;
// 是否开启网络 IP 转换器
private bool useNAT = false; private string ChatMessage = "Client Ready"; void OnGUI ()
{ switch (Network.peerType) {
case NetworkPeerType.Disconnected:
StartConnect ();
break;
case NetworkPeerType.Client:
ClientTo ();
break;
case NetworkPeerType.Connecting:
Debug.Log ("Connecting...");
break;
}
} void StartConnect ()
{
if (GUI.Button (new Rect (, , , ), "Connect Server")) {
NetworkConnectionError error = Network.Connect (remoteIP, listenPort, "UnityNetwork");
Debug.Log (error);
}
} void ClientTo ()
{ GUILayout.Label ("Connected"); } void OnConnectedToServer ()
{
// 通知场景中的物体已经与服务端连接
foreach (GameObject go in FindObjectsOfType(typeof(GameObject))) {
go.SendMessage ("OnNetworkLoaded", SendMessageOptions.DontRequireReceiver);
} } void OnDisconnectedFromServer (NetworkDisconnection info)
{ Network.RemoveRPCs (Network.player);
Network.DestroyPlayerObjects (Network.player);
Application.LoadLevel (Application.loadedLevel); } }