Unity中Websocket的简单使用

这篇博客介绍了如何在Unity中建立WebSocket连接,包括创建UI界面,使用BestHTTP插件,以及实现连接、发送、关闭WebSocket的方法。WebSocket服务器通过Tomcat搭建,当连接建立、接收到消息、错误发生或关闭时,会有相应的事件处理。此外,还提到了WebGL版本的测试和服务器端的反馈显示。
摘要由CSDN通过智能技术生成

首先我们需要一个websocket服务器,之前的博文中有做
Tomcat架设简单Websocket服务器
用的时候打开就行了,先不管它

Unity中新建场景
建UI(UGUI)
有一个连接按钮Button
一个信息输入框InputField
一个发送按钮Button
一个断开按钮Button
一个消息显示框Text
Unity中Websocket的简单使用

场景中建一个GameObject,在上面加个脚本,就叫WSMgr好了
用到了BestHTTP这个插件


  
  
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP;
  5. using BestHTTP.WebSocket;
  6. using System;
  7. using BestHTTP.Examples;
  8. using UnityEngine.UI;
  9. using System.Text;
  10. public class WSMgr : MonoBehaviour {
  11. //public string url = "ws://localhost:8080/web1/websocket";
  12. public string url = "ws://localhost:8080/web1/ws";
  13. public InputField msg;
  14. public Text console;
  15. private WebSocket webSocket;
  16. private void Start()
  17. {
  18. init();
  19. }
  20. private void init()
  21. {
  22. webSocket = new WebSocket( new Uri(url));
  23. webSocket.OnOpen += OnOpen;
  24. webSocket.OnMessage += OnMessageReceived;
  25. webSocket.OnError += OnError;
  26. webSocket.OnClosed += OnClosed;
  27. }
  28. private void antiInit()
  29. {
  30. webSocket.OnOpen = null;
  31. webSocket.OnMessage = null;
  32. webSocket.OnError = null;
  33. webSocket.OnClosed = null;
  34. webSocket = null;
  35. }
  36. private void setConsoleMsg(string msg)
  37. {
  38. console.text = "Message: " + msg;
  39. }
  40. public void Connect()
  41. {
  42. webSocket.Open();
  43. }
  44. private byte[] getBytes(string message)
  45. {
  46. byte[] buffer = Encoding.Default.GetBytes(message);
  47. return buffer;
  48. }
  49. public void Send()
  50. {
  51. webSocket.Send(msg.text);
  52. }
  53. public void Send(string str)
  54. {
  55. webSocket.Send(str);
  56. }
  57. public void Close()
  58. {
  59. webSocket.Close();
  60. }
  61. #region WebSocket Event Handlers
  62. /// <summary>
  63. /// Called when the web socket is open, and we are ready to send and receive data
  64. /// </summary>
  65. void OnOpen(WebSocket ws)
  66. {
  67. Debug.Log( "connected");
  68. setConsoleMsg( "Connected");
  69. }
  70. /// <summary>
  71. /// Called when we received a text message from the server
  72. /// </summary>
  73. void OnMessageReceived(WebSocket ws, string message)
  74. {
  75. Debug.Log(message);
  76. setConsoleMsg(message);
  77. }
  78. /// <summary>
  79. /// Called when the web socket closed
  80. /// </summary>
  81. void OnClosed(WebSocket ws, UInt16 code, string message)
  82. {
  83. Debug.Log(message);
  84. setConsoleMsg(message);
  85. antiInit();
  86. init();
  87. }
  88. private void OnDestroy()
  89. {
  90. if(webSocket!= null && webSocket.IsOpen)
  91. {
  92. webSocket.Close();
  93. antiInit();
  94. }
  95. }
  96. /// <summary>
  97. /// Called when an error occured on client side
  98. /// </summary>
  99. void OnError(WebSocket ws, Exception ex)
  100. {
  101. string errorMsg = string.Empty;
  102. #if !UNITY_WEBGL || UNITY_EDITOR
  103. if (ws.InternalRequest.Response != null)
  104. errorMsg = string.Format( "Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  105. #endif
  106. Debug.Log(errorMsg);
  107. setConsoleMsg(errorMsg);
  108. antiInit();
  109. init();
  110. }
  111. #endregion
  112. }

Connect Send Close 三个方法对应的就是三个按钮的功能
OnOpen OnMessage OnError OnClose这四个一看就是Websocket的四个事件对应的方法

首先在Start方法中init()
点击Connect,连接
Unity中Websocket的简单使用
在输入框中输入,点击Send就发送
Unity中Websocket的简单使用

点击Close断开连接
Unity中Websocket的简单使用
底部的Text中会显示消息

同样,Tomcat服务端也有显示 
Unity中Websocket的简单使用

发布WebGL测试可用

原文链接:http://blog.51cto.com/shuxiayeshou/2133714?source=dra

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值