Unity3d 网络编程(三)(Unity3d内建网络简单服务器的建立)

时间:2014-04-27 18:23:39   收藏:0   阅读:609

使用Unity3d的内建网络搭建一个简单的服务器,使用本机当主机,创建一个客户端连接到本机,


mamicode.com,码迷

mamicode.com,码迷

mamicode.com,码迷


我使用的NGUI作为主界面,服务器代码:

	string ipAddress = "127.0.0.1";
	int port = 23000;

	string msg = "";
	public UILabel lbl;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnClick () {
		if(Network.peerType == NetworkPeerType.Disconnected) {
			Network.InitializeServer(8, port, false);
			msg += "svr init";
			lbl.text = msg;
		} else {
			msg = "svr already start, connect type: " + Network.peerType;
			lbl.text = msg;
		}
	}

	void OnServerInitialized() {
		msg += "Server initialized and ready. ";
		lbl.text = msg;
	}

	void OnPlayerConnected(NetworkPlayer player) {
		msg = "Player connected from: " + player.ipAddress +":" + player.port;
		lbl.text = msg;
	}

	void OnPlayerDisconnected(NetworkPlayer player) {
		msg = "Player disconnected from: " + player.ipAddress+":" + player.port;
		lbl.text = msg;
	}

客户端代码:

string ipAddress = "127.0.0.1";
	int port = 23000;

	public UILabel lbl;

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void OnClick () {
		if( Network.peerType == NetworkPeerType.Disconnected ) {
			Network.Connect(ipAddress, port);
		}
	}


Unity3d 网络编程(三)(Unity3d内建网络简单服务器的建立),码迷,mamicode.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!