首页 > 代码库 > Unity3d 网络编程(三)(Unity3d内建网络简单服务器的建立)
Unity3d 网络编程(三)(Unity3d内建网络简单服务器的建立)
使用Unity3d的内建网络搭建一个简单的服务器,使用本机当主机,创建一个客户端连接到本机,
我使用的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); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。