redOrange

WebSocket.cs

Aug 28th, 2019
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Runtime.Serialization.Json;
  9. using System.Runtime.Serialization;
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. using System.Net.WebSockets;
  13.  
  14. public class SocketScript : MonoBehaviour
  15. {
  16.     public Button sendBtn;
  17.  
  18.     [HideInInspector]
  19.     public string json;
  20.     [HideInInspector]
  21.     public string playerStats;
  22.  
  23.     Uri u = new Uri("wss://yourURL");
  24.     ClientWebSocket cws = null;
  25.     ArraySegment<byte> buf = new ArraySegment<byte>(new byte[1024]);
  26.  
  27.     void Start()
  28.     {
  29.          Connect();
  30.  
  31.           Player player = new Player();
  32.           player.name = "Player Name";
  33.           player.money = 200;
  34.           json = JsonUtility.ToJson(player);
  35.     }
  36.  
  37.     public void Update()
  38.     {
  39.         if(cws.State != WebSocketState.Open)
  40.         {
  41.             sendBtn.interactable = false;
  42.         }
  43.         else
  44.         {
  45.             sendBtn.interactable = true;
  46.         }
  47.     }
  48.  
  49.     async void Connect() {
  50.         cws = new ClientWebSocket();
  51.         try {
  52.             await cws.ConnectAsync(u, CancellationToken.None);
  53.             if (cws.State == WebSocketState.Open) Debug.Log("connected");
  54.             GetValues();
  55.         }
  56.         catch (Exception e) { Debug.Log("woe " + e.Message); }
  57.     }
  58.  
  59.     public async void SendValues() {
  60.         ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(json));
  61.         await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
  62.     }
  63.  
  64.     async void GetValues() {
  65.         WebSocketReceiveResult r = await cws.ReceiveAsync(buf, CancellationToken.None);
  66.         Debug.Log("Server responds: " + Encoding.UTF8.GetString(buf.Array, 0, r.Count));
  67.         GetValues();
  68.     }
  69.  
  70.     [Serializable]
  71.     public class Player
  72.     {
  73.         public string name;
  74.         public int money;
  75.     }
Advertisement
Add Comment
Please, Sign In to add comment