温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Unity中Websocket的简单使用

发布时间:2020-02-23 01:06:05 来源:网络 阅读:21739 作者:lreach 栏目:游戏开发

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

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

(猜你喜欢:Unity 连接WebSocket(ws://)服务器的方法
Unity中Websocket的简单使用

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

(猜你喜欢:在Unity3d下如何使用WebSocket

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP;
using BestHTTP.WebSocket;
using System;
using BestHTTP.Examples;
using UnityEngine.UI;
using System.Text;

public class WSMgr : MonoBehaviour {

    //public string url = "ws://localhost:8080/web1/websocket";
    public string url = "ws://localhost:8080/web1/ws";
    public InputField msg;
    public Text console;

    private WebSocket webSocket;

    private void Start()
    {
        init();
    }

    private void init()
    {
        webSocket = new WebSocket(new Uri(url));
        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;
    }

    private void setConsoleMsg(string msg)
    {
        console.text = "Message: " + msg;
    }

    public void Connect()
    {
        webSocket.Open();
    }

    private byte[] getBytes(string message)
    {

        byte[] buffer = Encoding.Default.GetBytes(message);
        return buffer;
    }

    public void Send()
    {
        webSocket.Send(msg.text);
    }

    public void Send(string str)
    {
        webSocket.Send(str);
    }

    public void Close()
    {
        webSocket.Close();
    }

    #region WebSocket Event Handlers

    /// <summary>
    /// Called when the web socket is open, and we are ready to send and receive data
    /// </summary>
    void OnOpen(WebSocket ws)
    {
        Debug.Log("connected");
        setConsoleMsg("Connected");
    }

    /// <summary>
    /// Called when we received a text message from the server
    /// </summary>
    void OnMessageReceived(WebSocket ws, string message)
    {
        Debug.Log(message);
        setConsoleMsg(message);
    }

    /// <summary>
    /// Called when the web socket closed
    /// </summary>
    void OnClosed(WebSocket ws, UInt16 code, string message)
    {
        Debug.Log(message);
        setConsoleMsg(message);
        antiInit();
        init();
    }

    private void OnDestroy()
    {
        if(webSocket!=null && webSocket.IsOpen)
        {
            webSocket.Close();
            antiInit();
        }
    }

    /// <summary>
    /// Called when an error occured on client side
    /// </summary>
    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);
        setConsoleMsg(errorMsg);
        antiInit();
        init();
    }

    #endregion
}

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

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

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

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

发布WebGL测试可用

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI