Netty游戏服务器之三搭建Unity客户端

既然已经写完了相关的服务器处理类,那么我们就来搭建客户端测试一下。

 

打开我们的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)

好了测试相关的已经成功了,如果有什么问题可以留言给我,这个是我服务器写到一定程度才写这篇博文的,可能有步骤不对,你们尽管指出来。

posted @ 2015-06-30 12:06  草帽领  阅读(5958)  评论(7编辑  收藏  举报