码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-07-02 19:41:39      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:测试   gen   The   出现   closed   console   服务端   from   handle   

使用插件: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的,就这样了

 

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

标签:测试   gen   The   出现   closed   console   服务端   from   handle   

原文地址:https://www.cnblogs.com/zbyglls/p/11122146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!