Skip to content

Instantly share code, notes, and snippets.

@tmokmss
Last active April 28, 2018 09:01
Show Gist options
  • Save tmokmss/a6b849c0fdb5d975c410a84d0f344cfa to your computer and use it in GitHub Desktop.
Save tmokmss/a6b849c0fdb5d975c410a84d0f344cfa to your computer and use it in GitHub Desktop.
A successful WebSocket server and client set
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
public class EchoTest : MonoBehaviour {
WebSocket w;
int myid = -1;
public Text output;
bool isConnected = false;
// Use this for initialization
IEnumerator Start () {
//myid = UnityEngine.Random.Range(0, 10000);
w = new WebSocket(new Uri("ws://localhost:8080"));
yield return StartCoroutine(w.Connect());
StartCoroutine(SendSomething());
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
if (reply.StartsWith("id:"))
{
myid = int.Parse(reply.Substring(3));
isConnected = true;
}
Debug.Log ("Received: "+reply);
output.text += reply;
}
if (w.error != null)
{
Debug.LogError ("Error: "+w.error);
output.text += w.error;
break;
}
yield return 0;
}
}
IEnumerator SendSomething()
{
while (true)
{
if (isConnected)
{
w.SendString(string.Format("me:{0}", myid));
}
yield return new WaitForSeconds(1);
}
}
private void OnApplicationQuit()
{
w.Close();
}
}
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
var latestid = 0;
wss.on('connection', function connection(ws) {
ws.send('id:' + latestid);
latestid += 1;
ws.on('message', function incoming(message) {
console.log('received: %s', message);
// Broadcast to everyone else.
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.on('close', function close() {
console.log('disconnected');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment