unity使用websocket

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP.WebSocket;
using System;
using Newtonsoft.Json.Linq;
using UnityEngine.UI;
public class server : MonoBehaviour
{
    WebSocket client;
   
    string url = 
    
    public int type;//参数类型
    public string deviceld;//设备id
    public string taskId;//任务id
    public int status;//任务状态
    public string tasktime;
    public  string startTime;//任务开始时间
    public  string endTime;//任务结束时间
    public  int sceneId;//场景id
    public int time;//播放时长
    private int overtype;
    public  string SystemTime;
    public static server instance;
    private Canvas canvas;
    private void Start()
    {

      // Unity.XR.PXR.PXR_System.AppKeepAlive("com.HXQ.MXLY",true,1);
#if UNITY_EDITOR
        deviceld = "1983cd060b216226b4b18e6c01775e617a93e33a";
#else 
 deviceld = SystemInfo.deviceUniqueIdentifier.ToString();
#endif
        Debug.Log("w1:" + SystemInfo.deviceUniqueIdentifier.ToString());
        canvas = this.GetComponent<Canvas>();
        canvas.overrideSorting = true;
        canvas.sortingOrder = 1;
        ConnectServer();
    }
    /// <summary>
    /// 初始化websocket
    /// </summary>
    public void ConnectServer()
    {
        client = new WebSocket(new System.Uri(url));//websocket访问地址
        RemHead();
        client.OnOpen += OnOpen;
        client.OnMessage += OnMessage;
        client.OnError += OnError;
        client.Open();
    }


   public void RemHead()
   {
        client.OnMessage -= OnMessage;
        client.OnError -= OnError;
        client.OnOpen -= OnOpen;
   }



#region 开始登录和心跳
    public void OnOpen(WebSocket websocket)
    {
        LoginProt(deviceld);
        StartCoroutine(UpdataBattery());
    }
    IEnumerator UpdataBattery()
    {
        while (true)
        {
            Heart(deviceld);
            yield return new WaitForSeconds(10f);
        }
    }
    int batterytype;
    public void Heart(string DeviceID)
    {
        
        if (SystemInfo.batteryStatus.ToString() == "Charging") batterytype = 1; //充电中
        else batterytype = 0;//未充电

        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["deviceId"] = DeviceID;
        jd["type"] = 10;
        jd["chargeStatus"] = batterytype;
#if UNITY_EDITOR
        jd["soc"] = 0;
#else
          float f= SystemInfo.batteryLevel * 100;
          jd["soc"] = (int)f;
#endif
        client.Send(jd.ToJson());
        Debug.Log("发送心跳成功'''''''"+ jd.ToJson());
    }
    #endregion

#region  发送消息报错
    public void OnError(WebSocket webSocket, Exception ex)
    {
        if (ex != null)
            Debug.Log("OnError: " + ex.Message);
        client.Close();
        Reconnection();
        //InvokeRepeating("Reconnection", 1f, 1);
    }
 
    public void Reconnection()
    {
        ConnectServer();
    }
#endregion

   
#region 登录接口和信息
    public void LoginProt(string devicedID)
    {
        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["deviceId"] = devicedID;
        jd["type"] = 0;
        client.Send(jd.ToJson());
        Debug.Log("websocket登录成功");
    }

    public void LoginMessage(string s)
    {
        CancelInvoke("Reconnection");
        wsMessage obj = JsonUtility.FromJson<wsMessage>(s);
        Debug.Log("LgingMessage +  TYPE" + obj.type);
        if (obj.type == 1)
        {
            type = 1;
        }
        
    }
#endregion
#region 服务器下发任务后做出响应
    public void RecevieTaskMessage(string s)
    {
        wsMessage obj = JsonUtility.FromJson<wsMessage>(s);
        if (obj.type == 1)
        {
            type = 2;
            taskId = obj.taskId;
            sceneId = obj.sceneId;
            time = obj.time;
            Infolsit.instance.GetViedoList(obj.sceneId);
            Debug.Log("obj.sceneId:   " + obj.sceneId);
            PlayerPrefs.SetInt("sceneId", sceneId);
            PlayerPrefs.SetString("taskId", taskId);
            PlayerPrefs.SetInt("time", time);
            Debug.Log(PlayerPrefs.GetString("taskId"));
            RecevieTask(deviceld);
        }
    }
    public void RecevieTask(string DevicedID)
    {
        PlayerPrefs.SetInt("status",0);//待训练任务
        LitJson.JsonData res = LitJson.JsonMapper.ToObject("");
        res["taskId"] = taskId;
        res["status"] = "1";
        res["overType"] = "-1";
        res["taskTime"] = GetTime();
        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["code"] = "200";
        jd["message"] = "OK";
        jd["deviceId"] =DevicedID;
        jd["taskId"] = taskId;
        jd["result"] = res;
        jd["type"] = type;
        client.Send(jd.ToJson());
    }
#endregion

#region 服务器发出终止任务,做出响应
    public void TerminatedTaskMesssage(string s)
    {
        Debug.Log("TerminatedTaskMesssage : " + s);
        wsMessage wm = JsonUtility.FromJson<wsMessage>(s);
        type = wm.type;
        if (wm.taskId == taskId && wm.type == type)
        {
            TerminatedTask();
            HosMed.instance.EndOrStop();
        }
           
    }
    public void TerminatedTask()
    {
        PlayerPrefs.SetInt("status", 4);//异常终止
        LitJson.JsonData res = LitJson.JsonMapper.ToObject("");
        res["taskId"] = taskId;
        res["status"] = "4";
        res["overType"] = "2";
#if UNITY_EDITOR
        res["soc"] = 0;
#else
         float f= SystemInfo.batteryLevel * 100;
         res["soc"] = (int)f;
#endif
        res["taskTime"] = GetTime();
        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["code"] = "200";
        jd["message"] = "OK";
        jd["taskId"] = taskId;
        jd["result"] = res;
        jd["type"] = 2;
        jd["deviceId"] = deviceld;
        client.Send(jd.ToJson());
    }
#endregion

#region 开始任务  头盔观看UI 2秒后开始任务

    public void GetStartTask()
    {
        StartTask(deviceld, taskId);
    }

    public void StartTask(string devicedID, string TaskId)
    {
        PlayerPrefs.SetInt("status", 2);//训练中
        wsMessage.TaskType = "已开始任务";
        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["deviceId"] = devicedID;
        jd["type"] = 5;
        jd["taskId"] = TaskId;
        jd["status"] = 2;
        jd["startTime"] = GetTime();
#if UNITY_EDITOR
        jd["soc"] = 0;
#else
         float f= SystemInfo.batteryLevel * 100;
          jd["soc"] = (int)f;
#endif
        client.Send(jd.ToJson());
    }

    public void StarTaskMessage(string s)
    {
        Debug.Log("StarTask :   " + s);
    }
#endregion

#region 结束任务
    public void GetTaskOver()
    {
        TaskOver(deviceld, taskId);
    }
    public void TaskOver(string devicedID, string TaskID)
    {
        PlayerPrefs.SetInt("status", 3);//训练完成
        LitJson.JsonData jd = LitJson.JsonMapper.ToObject("");
        jd["deviceId"] = devicedID;
        jd["type"] = 6;
        jd["taskId"] = TaskID;
        jd["status"] = 3;
        jd["endTime"] = GetTime();
#if UNITY_EDITOR
        jd["soc"] = 0;
#else
        float f= SystemInfo.batteryLevel * 100;
          jd["soc"] = (int)f;
#endif
        client.Send(jd.ToJson());
    }
    public void TaskOverMesssage(string s)
    {
        Debug.Log("TaskOverMesssage: " + s);
    }
    #endregion


    public void NewMessage(string m)
    {
        Debug.Log("NewMessage: " + m);
        wsMessage ws = JsonUtility.FromJson<wsMessage>(m);
        if (ws.type == 7)
        {
            HosMed.instance.StateString = "设备启动";
            HosMed.instance.statemodel();
            wsMessage.TaskType = "未开始任务";
        }
    }


    public void QueryTaskMessage(string mes)
    {
        Debug.Log("QueryTaskMessage:  " + mes);
        wsMessage ws = JsonUtility.FromJson<wsMessage>(mes);
        PlayerPrefs.SetString("taskid", ws.taskId);
        Debug.Log("status:   " + PlayerPrefs.GetInt("status"));
        if (ws.status == 1 && PlayerPrefs.GetInt("status") < 2)
        {
            Infolsit.instance.GetViedoList(PlayerPrefs.GetInt("sceneId"));
            PlayerPrefs.SetInt("status", ws.status);
            HosMed.instance.StateString = "设备重连";
            HosMed.instance.statemodel();
            wsMessage.TaskType = "未开始任务";
        }
        if (ws.type == 4)
        {
            if (ws.status == 2)
            {
                if (HosMed.instance.VideoPlayer360.clip.name == "大厅背景")
                {
                    Debug.Log("设备已经重启或者关机啦,关闭这个任务吧!");
                    QureyTask(deviceld, 4,"1");
                }
                else
                {
                    QureyTask(deviceld, PlayerPrefs.GetInt("status"),"0");
                }
            }
            Debug.Log("任务状态是什么:    ______" + ws.status);
        }
    }

  

    public void QureyTask(string devicedID,int status,string overtype)
    {
        LitJson.JsonData res = LitJson.JsonMapper.ToObject("");
        res["taskId"] = PlayerPrefs.GetString("taskid");
        res["status"] = status;
        res["taskTime"] = tasktime;
        //res["startTime"] = PlayerPrefs.GetString("StartTime");
        res["startTime"] =startTime;
        res["endTime"] = endTime;
        // res["endTime"] = PlayerPrefs.GetString("EndTime");
        Debug.Log("NowTime_____" + PlayerPrefs.GetInt("playSecond"));
        res["playSecond"] = PlayerPrefs.GetInt("playSecond");
        res["overType"] = overtype;
        LitJson.JsonData jd = new LitJson.JsonData();
        jd["code"] = "200";
        jd["message"] = "OK";
        jd["deviceId"] = devicedID;
        jd["taskId"] = PlayerPrefs.GetString("taskid");
        jd["result"] = res;
        jd["type"] = 2;
        client.Send(jd.ToJson());
        Debug.Log("重连数据:   "+jd.ToJson());
    }

private void OnMessage(BestHTTP.WebSocket.WebSocket webSocket, string message)
    {
        wsMessage wm = JsonUtility.FromJson<wsMessage>(message);
        switch(wm.type)
        {
            case 0:
                LoginMessage(message);
                break;
            case 1:
                RecevieTaskMessage(message);
                break;
            case 3:
                TerminatedTaskMesssage(message);
                break;
            case 4:
                QueryTaskMessage(message);
                break;
            case 7:
                NewMessage(message);
                break;
            default:
                Debug.Log("message: "+ message  + "    wm.type:  " + wm.type);
                break;
        }
    }

   

#region 当前时间
    public string GetTime()
    {
        int hour = DateTime.Now.Hour;
        int minute = DateTime.Now.Minute;
        int second = DateTime.Now.Second;
        int year = DateTime.Now.Year;
        int month = DateTime.Now.Month;
        int day = DateTime.Now.Day;

        //格式化显示当前时间
        SystemTime = string.Format("{0:D2}-{1:D2}-{2:D2} " + "{3:D2}:{4:D2}:{5:D2}", year, month, day, hour, minute, second);
        return SystemTime;
    }
#endregion


}
public class wsMessage
{
    public static  string TaskType= "未接收任务";//任务状态
    public int type;//参数类型
    public string tasktime;
    public string deviceld;//设备id
    public int status;//任务状态
    public string startTime;//任务开始时间
    public string endTime;//任务结束时间
    public int soc;//电量百分比
    public string taskId;//任务id
    public string patientName;//患者姓名
    public string patientId;//患者id
    public  int sceneId;//场景id
    public  int time;//播放时长
    public string code;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值