Unity3D关于WebSocket的实现(一) 您所在的位置:网站首页 lua连接websocket Unity3D关于WebSocket的实现(一)

Unity3D关于WebSocket的实现(一)

2024-03-31 00:18| 来源: 网络整理| 查看: 265

前情概要

服务端使用的是SpringBoot,详情实现方式请阅读

SpringBoot及Construct2关于WebSocket的实现(一)

为了使同个服务端不同游戏引擎都可以用,后面我会用Json插件将它们封装成Json字符串进行传输通信

一、介绍

使用Unity3D做为WebSocket客户端,主要是使用了一个插件BestHttp(你懂的)

放上下载链接: Best HTTP - Assert Store

或者:[工具]U3D BestHTTP

因为使用过程中一切顺利~参考博客

Unity中Websocket的简单使用

会有后续开发日志,这篇算作也是初学者第一步。

二、Unity3D界面

1、InputField是输入框,和上一篇一样需要先传一个id进行webSocket连接

2、connect和send是按钮

3、log是日志显示(接收信息之类)

4、websocket是一个空物体,用来绑定C#脚本

三、主程序编写 1、导入资源包

除了Example文件目录,其它都导入。

2、创建绑定脚本

这里我创建了一个WebSocketServer脚本用来管理整个WebSocket连接

引入的命名空间:

using UnityEngine; using BestHTTP; using BestHTTP.WebSocket; using UnityEngine.UI; using System; using System.Text;

连接初始化和关闭方法

public string url = "ws://localhost:8080//websocket/"; public InputField msg; public Text log; private WebSocket webSocket; private void Init(string id) { webSocket = new WebSocket(new Uri(url+id)); webSocket.OnOpen += OnOpen; webSocket.OnMessage += OnMessageReceived; webSocket.OnError += OnError; webSocket.OnClosed += OnClosed; } private void AntiInit() { webSocket.OnOpen = null; webSocket.OnMessage = null; webSocket.OnError = null; webSocket.OnClosed = null; webSocket = null; }

讲解:

OnOpen是一个方法,然后用+=形式来调用,很明显这是一个响应事件Event,使用注册事件的形式来初始化websocket连接

建立连接:

/// /// 连接时 /// /// void OnOpen(WebSocket ws) { Debug.Log("connecting..."); SetLog("connecting..."); }

接收信息:

/// /// 接收时 /// /// /// void OnMessageReceived(WebSocket ws,string msg) { Debug.Log(msg); SetLog(msg); }

关闭连接:

/// /// 关闭时 /// /// /// /// void OnClosed(WebSocket ws, UInt16 code, string msg) { Debug.Log(msg); SetLog(msg); AntiInit(); }

响应错误:

/// /// 错误时 /// /// /// void OnError(WebSocket ws, Exception ex) { string errorMsg = string.Empty; #if !UNITY_WEBGL || UNITY_EDITOR if (ws.InternalRequest.Response != null) errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message); #endif Debug.Log(errorMsg); SetLog(errorMsg); AntiInit(); }

连接按钮:

public void Connect() { string id = msg.text; Init(id); webSocket.Open(); }

发送按钮:

public void Send() { webSocket.Send(msg.text); } 3、将按钮和输入框进行事件绑定 四、实际结果 1、将Unity工程打包成.exe文件

2、启动服务器,及两次客户端程序

这里的服务器错误是因为,我没有调用关闭连接的方法,我是直接关掉程序的...(捂脸)

五、总结

1、很长时间没写C#了,手生到爆炸,好在java语法与C#语法也算是比较相似了~~

2、Unity3D为做一个联机游戏,需要达到消息同步的目的,才用一个Socket来做管理。

3、最后,说一句,待更新!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有