Unity3d 网络编程(三)(Unity3d内置简单的网络server编制)

使用Unity3d内置的网络建立一个简单的server。主机时,请使用机器。创建一个client连接到本机。






我使用的NGUI作为主界面,server代码:

	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;
	}

client代码:

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);
		}
	}


版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-08-19 21:16  blfshiye  阅读(364)  评论(0编辑  收藏  举报