• 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)

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

  • 相关阅读:
    idea配置tomcat
    使用svn时出现Can't switch /XXX/XXX because it is not the repository yet
    使用idea断点调试时出现no executable code found at line问题
    python 发送邮件
    python中子类调用父类的方法
    Java源码阅读PriorityQueue
    comparable和comparator
    java源码阅读LinkedBlockingQueue
    java源码阅读ArrayBlockingQueue
    java源码阅读LinkedList
  • 原文地址:https://www.cnblogs.com/CaomaoUnity3d/p/4610034.html
Copyright © 2020-2023  润新知