I 'am following this guide to build a WebGL project with WebSockets.
In Editor, it is worked. The client can send and receive message from server. However, build on WebGL is not working. The client can send message to server but can’t receive message from server. Any step I miss? Or anyone can help me? Thanks.
Sever code:
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
using System.Security.Cryptography.X509Certificates;
namespace Example
{
public class Echo : WebSocketBehavior
{
protected override void OnMessage(MessageEventArgs e)
{
var msg = System.Text.Encoding.UTF8.GetString(e.RawData);
Console.WriteLine("Got Message: " + msg);
Send(msg);
}
}
public class Program
{
public static void Main (string[] args)
{
var wssv = new WebSocketServer (9000, true);
wssv.SslConfiguration.ServerCertificate =
new X509Certificate2 ("cert.pfx");
wssv.AddWebSocketService<Echo> ("/echo");
wssv.Start ();
Console.Read();
wssv.Stop ();
}
}
}
Client code in Unity:
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
// Use plugin namespace
using HybridWebSocket;
public class WebSocketDemo : MonoBehaviour {
// Use this for initialization
void Start () {
// Create WebSocket instance
WebSocket ws = WebSocketFactory.CreateInstance("ws://localhost:9000/echo");
// Add OnOpen event listener
ws.OnOpen += () =>
{
Debug.Log("WS connected!");
Debug.Log("WS state: " + ws.GetState().ToString());
ws.Send(Encoding.UTF8.GetBytes("Hello from Unity 3D!"));
};
// Add OnMessage event listener
ws.OnMessage += (byte[] msg) =>
{
Debug.Log("WS received message: " + Encoding.UTF8.GetString(msg));
ws.Close();
};
// Add OnError event listener
ws.OnError += (string errMsg) =>
{
Debug.Log("WS error: " + errMsg);
};
// Add OnClose event listener
ws.OnClose += (WebSocketCloseCode code) =>
{
Debug.Log("WS closed with code: " + code.ToString());
};
// Connect to the server
ws.Connect();
}
// Update is called once per frame
void Update () {
}
}