zoukankan      html  css  js  c++  java
  • 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)

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

  • 相关阅读:
    PAT 1010. 一元多项式求导 (25)
    PAT 1009. 说反话 (20) JAVA
    PAT 1009. 说反话 (20)
    PAT 1007. 素数对猜想 (20)
    POJ 2752 Seek the Name, Seek the Fame KMP
    POJ 2406 Power Strings KMP
    ZOJ3811 Untrusted Patrol
    Codeforces Round #265 (Div. 2) 题解
    Topcoder SRM632 DIV2 解题报告
    Topcoder SRM631 DIV2 解题报告
  • 原文地址:https://www.cnblogs.com/CaomaoUnity3d/p/4610034.html
Copyright © 2011-2022 走看看