既然已經寫完了相關的服務器處理類,那么我們就來搭建客戶端測試一下。
打開我們的unity3d,然后新建一個c#腳本,取名為MainClient。
public class MainClient : MonoBehaviour{ private const string HOST = "127.0.0.1"; private const int PORT = 8080; public static MainClient instance; public static TcpClient client; void Awake() { if (instance == null) { instance = this; DontDestroyOnLoad(this.gameObject); } } void Start() { if (client == null) { Connect(); } } void Update() { } void OnApplicationQuit() { client.Close(); } public void Connect() { client = new TcpClient(); try{ client.Connect(HOST,PORT); }catch(Exception e){ Debug.LogException(e); client.Close(); } } }
然后再Hierarchy窗口新建一個gameobject,將MainClient賦給它,將之做成prefab。
好了,我們先啟動服務器,再啟動我們的unity3d工程,會發現呢
服務器會跳轉到之前我們寫的處理類ServerHandler的方法,public void channelActive(ChannelHandlerContext ctx),打印這句話,channel.id()就是唯一標識該客戶端,感興趣的童鞋可以去學習netty的源代碼。
當我們斷開unity3d客戶端,就會調用public void channelInactive(ChannelHandlerContext ctx)
好了測試相關的已經成功了,如果有什么問題可以留言給我,這個是我服務器寫到一定程度才寫這篇博文的,可能有步驟不對,你們盡管指出來。