Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net.WebSockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using UnityEngine;
- // To test:
- // - Place this component on an object in the scene
- // - Visit https://socketsbay.com/test-websockets and click Connect
- // - Press play in Unity
- // - Wait for the name prompt on the socketsbay website
- // - Enter a name and click Send
- // - Wait for response greeting
- public class Connection : MonoBehaviour
- {
- ClientWebSocket websocket;
- async void Start()
- {
- websocket = new ClientWebSocket();
- await websocket.ConnectAsync(new Uri("wss://socketsbay.com/wss/v2/1/demo/"), CancellationToken.None);
- // Begin routine
- TestRoutine();
- }
- public async void TestRoutine()
- {
- // Greeting
- SendWebSocketMessage("Hello, what is your name?");
- // Wait for response
- string name = await ReceiveWebSocketMessage();
- // Response
- SendWebSocketMessage("Hello " + name);
- }
- public void SendWebSocketMessage(string msg)
- {
- websocket.SendAsync(Encoding.UTF8.GetBytes(msg), WebSocketMessageType.Text, true, CancellationToken.None);
- }
- public async Task<string> ReceiveWebSocketMessage()
- {
- var recvBuffer = new byte[1024];
- var result = await websocket.ReceiveAsync(recvBuffer, CancellationToken.None);
- return Encoding.UTF8.GetString(recvBuffer, 0, result.Count);
- }
- void OnApplicationQuit()
- {
- websocket.CloseAsync(WebSocketCloseStatus.Empty, "", CancellationToken.None);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement