Unity3d websocket + simplejson解析不起作用

时间:2016-01-21 17:23:05

标签: json unity3d websocket

我有问题,我的while(循环)不能真正起作用。它是Unity3D的免费websocket资产的修改示例。我可以将json发送到我的node.js服务器,但我无法收到json。显然循环或接收字符串肯定有问题。因为我的Debug.Log只播放一次(只有第一次“while”)。如果我做了if reply == null,那么我将再次收到一个日志。所以似乎没有数据到达...但是我的Loop不应该一直工作,只是只玩一次?

也许你可以帮助我摆脱困境。非常感谢你! :)

using UnityEngine;
using System.Collections;
using System;
using SimpleJSON;

public class EchoTest : MonoBehaviour {

    // Use this for initialization
    IEnumerator Start () {
        WebSocket w = new WebSocket(new Uri("ws://localhost:8000/2"));
        yield return StartCoroutine(w.Connect());

        var N = new JSONClass();
        String P;
        N.Add("id", "unityclient");
        N.Add("to", "htmlclient");
        P = N.ToString();
        w.SendString(P);


        int i=0;
        while (true)
        {
            Debug.Log("while");
            string reply = w.RecvString();
            if (reply != null){
                Debug.Log("while2");
                var rep = JSON.Parse(reply);
                Debug.Log("jo");
                string jdata = rep["data"];
                Debug.Log(jdata);
                i++;
            }

            /*
            if (reply!="red"){
                Debug.Log ("Received: "+reply);
            }

            if (reply=="red"){
                var replydata = JSONNode.Parse(reply);
                var userid = replydata["data"]["userid"];
                var message = replydata["data"]["message"];
                Debug.Log(userid+":"+message);
            }

            if (reply == "red")
            {
                Debug.Log ("Received: "+reply);
                w.SendString("red back");
            }*/
            if (w.error != null)
            {
                Debug.LogError ("Error: "+w.error);
                break;
            }
            yield return 0;
        }
        w.Close();
    }
}

使用节点js服务器代码可能会有所帮助:

// Websocket-Server
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({host: 'localhost',port: 8000});


wss.on('connection', function(ws) 
{
    var clients = {};

    console.log('client verbunden...');


    ws.on('message', function (data) {
    console.log('von Client empfangen: '+data );
    var obj = JSON.parse(data);

          if("id" in obj) {
            // New client, add it to the id/client object
            clients[obj.id] = obj.id;
            console.log('client: ' + obj.id);
          } 
          else {
            // Send data to the client requested
            clients[obj.to].send(obj.data);
            console.log('send: ' + obj.data);
          }
    })
     /* ws.on('message', function(message) 
    {
        console.log('von Client empfangen: ' + message);
        ws.send('von Server empfangen: ' + message);
    });*/

});

0 个答案:

没有答案