- Home /
WebSocket and WebGL error
Hi there, I'm trying to use this free websocket pack with Unity. The demo works ok.
But now I need to do something more real. I'm trying to built a Server C# (console app) to run on Windows and make the Unity WebGL client to connect to it. My server code follows this example.
Server code:
class Program
{
public static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
server.Start();
Console.WriteLine("Server is running 127.0.0.1:8080");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client accepted");
NetworkStream stream = client.GetStream();
//loop to handle the stream
while (true)
{
while (!stream.DataAvailable) { };
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
Console.WriteLine("Data> " + Encoding.UTF8.GetString(bytes));
var data = Encoding.UTF8.GetString(bytes);
if (new Regex("^GET").IsMatch(data))
{
Console.WriteLine("GET");
SHA1 sha1 = SHA1.Create();
Byte[] response = Encoding.UTF8.GetBytes(
"HTTP/1.1 101 Switching Protocols" + Environment.NewLine +
"Upgrade: websocket" + Environment.NewLine +
"Connection: Upgrade" + Environment.NewLine +
"Sec-WebSocket-Accept" + Convert.ToBase64String(
sha1.ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine + Environment.NewLine);
}
else
Console.WriteLine("!GET");
}
}
}
And here is the client code:
public class EchoTest : MonoBehaviour
{
IEnumerator Start()
{
WebSocket w = new WebSocket(new Uri("ws://localhost:8080"));
yield return StartCoroutine(w.Connect());
w.SendString("Hi there");
int i = 0;
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
Debug.Log("Received: " + reply);
t.text = reply;
w.SendString("Hi there" + i++);
}
if (w.error != null)
{
Debug.LogError("Error: " + w.error);
w.Close();
yield return StartCoroutine(w.Connect());
break;
}
yield return 0;
}
w.Close();
}
}
When I run the server and unity, the server actually print the line "GET" on console, but nothing happens after. The unity then print the error message on block "if (w.error != null)":
Error: The WebSocket connection has already been closed. UnityEngine.Debug:LogError(Object) c__Iterator0:MoveNext() (at Assets/Example/EchoTest.cs:28)
How can I exchange messages between then? What am I doing wrong or missing?
Thanks.
Answer by SunnyChow · Feb 24, 2016 at 02:34 AM
I don't think Unity WebGL would support your plugin (which include a dll file), and some of the .NET classes you are using. I guess you probably should write a web socket feature in html way and make Unity to call it.
Also, did you test the server works? Anyways, I am using NodeJS to run my web socket server