当前位置:   article > 正文

unity使用websocket_unity websocket

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358
  • 359
  • 360
  • 361
  • 362
  • 363
  • 364
  • 365
  • 366
  • 367
  • 368
  • 369
  • 370
  • 371
  • 372
  • 373
  • 374
  • 375
  • 376
  • 377
  • 378
  • 379
  • 380
  • 381
  • 382
  • 383
  • 384
  • 385
  • 386
  • 387
  • 388
  • 389
  • 390
  • 391
  • 392
  • 393
  • 394
  • 395
  • 396
  • 397
  • 398
  • 399
  • 400
  • 401
  • 402
  • 403
  • 404
  • 405
  • 406
  • 407
  • 408
  • 409
  • 410
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/107320
推荐阅读
相关标签
  

闽ICP备14008679号