u3d:使用websocket最简单的测试通信

使用插件:besthttp 1.10

u3d版本:5.4.0

代码:找的网上的一篇代码,自己偷懒没写 只简单测试了下

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";
    [SerializeField]
    private string url;
    public InputField msg;
    public Text console;

    private WebSocket webSocket;

    private void Start()
    {
        init();
        print("执行");
        //WebSocket1();
    }
    void Update()
    {
        print(webSocket.IsOpen);

       
    }


    void WebSocket1()
    {
        WebSocket webSocket = new WebSocket(new Uri(url));
        //webSocket.OnOpen...
        //注册事件之后,我们就可以开始连接
        webSocket.Open();
        //在这一步之后,我们将收到一个OnOpen事件,我们可以开始发送消息到服务器
        webSocket.Send("Message to the Server");
        byte[] buffer = new byte[1024];
        webSocket.Send(buffer);
        //所有通信完成之后,就关闭连接
        webSocket.Close();
    }




    private void init()
    {
        webSocket = new WebSocket(new Uri(url));
        webSocket.OnOpen += OnOpen;
        webSocket.OnMessage += OnMessageReceived;
        webSocket.OnError += OnError;
        webSocket.OnClosed += OnClosed;

        webSocket.Open();
        print("执行这里");
        
    }

    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();
        print(webSocket!=null);
    }

    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 + "close");
        //   setConsoleMsg(message);
        //antiInit();
        //  init();
    }
    //void OnApplicationQuit
    void OnApplicationQuit()
    {
        //print(webSocket.IsOpen);
        //if (webSocket != null && webSocket.IsOpen)
        //{
        print("quit");
        //    webSocket.Close();
        //    //antiInit();
        //}

    }
    private void OnDestroy()
    {
        print("destory");

        //if (webSocket != null && webSocket.IsOpen)
        //{
        //    print("destory");
        //    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
}

脚本中对应的方法填入到对应的button中,执行,不需要切换成webgl直接PC端测试能用,
服务端测试地址:http://ruyice.com/test  我是在这个网址中的websocket进行测试的,不用自己麻烦的搭建服务端

在脚本中的url中填写上图中的测试ws网址:ws://demos.kaazing.com/echo

测试结果:

 能运行,测试过程中出现的问题,如果在OnDestory()和OnApplicationQuit()中使用websocket.close()的话就会报错,虽然不影响什么,但是总看着不舒服,所以直接把close方法去掉了,程序关掉的同时也关掉了websocket的,就这样了

猜你喜欢

转载自www.cnblogs.com/zbyglls/p/11122146.html