Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using System;
- using System.IO;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Runtime.Serialization.Json;
- using System.Runtime.Serialization;
- using UnityEngine;
- using UnityEngine.UI;
- using System.Net.WebSockets;
- public class SocketScript : MonoBehaviour
- {
- public Button sendBtn;
- [HideInInspector]
- public string json;
- [HideInInspector]
- public string playerStats;
- Uri u = new Uri("wss://yourURL");
- ClientWebSocket cws = null;
- ArraySegment<byte> buf = new ArraySegment<byte>(new byte[1024]);
- void Start()
- {
- Connect();
- Player player = new Player();
- player.name = "Player Name";
- player.money = 200;
- json = JsonUtility.ToJson(player);
- }
- public void Update()
- {
- if(cws.State != WebSocketState.Open)
- {
- sendBtn.interactable = false;
- }
- else
- {
- sendBtn.interactable = true;
- }
- }
- async void Connect() {
- cws = new ClientWebSocket();
- try {
- await cws.ConnectAsync(u, CancellationToken.None);
- if (cws.State == WebSocketState.Open) Debug.Log("connected");
- GetValues();
- }
- catch (Exception e) { Debug.Log("woe " + e.Message); }
- }
- public async void SendValues() {
- ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(json));
- await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
- }
- async void GetValues() {
- WebSocketReceiveResult r = await cws.ReceiveAsync(buf, CancellationToken.None);
- Debug.Log("Server responds: " + Encoding.UTF8.GetString(buf.Array, 0, r.Count));
- GetValues();
- }
- [Serializable]
- public class Player
- {
- public string name;
- public int money;
- }
Advertisement
Add Comment
Please, Sign In to add comment