unity项目 websocket

本文介绍了如何在Unity中使用C#的WebSocketAPI进行WebSocket连接,包括创建WebSocket对象、连接服务器、实时接收和解析数据的过程。
摘要由CSDN通过智能技术生成

拷贝即用(加个你自己的userID):

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class ConnetWebSocket : MonoBehaviour
{
    private ClientWebSocket ws;
    private void Start()
    {
        WebSocket();
    }

    public async void WebSocket()
    {
        try
        {
            ws = new ClientWebSocket();
            CancellationToken ct = new CancellationToken();
            Uri url = new Uri("ws://127.0.0.1:9999/test/websocket/" + {your userID});

            await ws.ConnectAsync(url, ct);
            while (true)
            {
                var result = new byte[1024];
                await ws.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
                var str = Encoding.UTF8.GetString(result, 0, result.Length);
                Debug.Log("web conection receive : " + str);

                ReceiveDataModel receiveData = JsonUtility.FromJson<ReceiveDataModel>(str);
                if (receiveData.msgId == 1001)
                {
                    Debug.Log("收到指令...");
                    //do...
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    private void OnDestroy()
    {
        if(ws != null) ws.Dispose();
    }
}

[SerializeField]
public class ReceiveDataModel
{
    public int msgId;
    public string content;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值