Advertisement
Weesals

Websocket example test script

Jul 30th, 2023 (edited)
1,486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2. using System.Net.WebSockets;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7.  
  8. // To test:
  9. // - Place this component on an object in the scene
  10. // - Visit https://socketsbay.com/test-websockets and click Connect
  11. // - Press play in Unity
  12. // - Wait for the name prompt on the socketsbay website
  13. // - Enter a name and click Send
  14. // - Wait for response greeting
  15. public class Connection : MonoBehaviour
  16. {
  17.     ClientWebSocket websocket;
  18.    
  19.     async void Start()
  20.     {
  21.         websocket = new ClientWebSocket();
  22.         await websocket.ConnectAsync(new Uri("wss://socketsbay.com/wss/v2/1/demo/"), CancellationToken.None);
  23.  
  24.         // Begin routine
  25.         TestRoutine();
  26.     }
  27.  
  28.     public async void TestRoutine()
  29.     {
  30.         // Greeting
  31.         SendWebSocketMessage("Hello, what is your name?");
  32.         // Wait for response
  33.         string name = await ReceiveWebSocketMessage();
  34.         // Response
  35.         SendWebSocketMessage("Hello " + name);
  36.     }
  37.  
  38.     public void SendWebSocketMessage(string msg)
  39.     {
  40.         websocket.SendAsync(Encoding.UTF8.GetBytes(msg), WebSocketMessageType.Text, true, CancellationToken.None);
  41.     }
  42.     public async Task<string> ReceiveWebSocketMessage()
  43.     {
  44.         var recvBuffer = new byte[1024];
  45.         var result = await websocket.ReceiveAsync(recvBuffer, CancellationToken.None);
  46.         return Encoding.UTF8.GetString(recvBuffer, 0, result.Count);
  47.     }
  48.     void OnApplicationQuit()
  49.     {
  50.         websocket.CloseAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
  51.     }
  52.  
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement