2016-12-15 1 views
1

저는 Primus를 사용하여 websocket 서버를 만듭니다. 그리고 wscat 명령을 사용하여 해당 서버를 테스트합니다. websocket 서버에 연결할 수 있습니다. 그러나 서버는 클라이언트로부터 메시지를 수신 할 수 없습니다. 아래Primus websocket 서버가 클라이언트의 메시지를 읽지 못했습니다.

http = require('http'); 
server = http.createServer(); 

Primus = require('primus'); 
primus = new Primus(server, { 
    transformer: 'websockets', 
    pathname: 'ws' 
}); 

primus.on('connection', function connection(spark) { 
    console.log("client has connected"); 
    spark.write("Herro Client, I am Server"); 
    spark.on('data', function(data) { 
    console.log('PRINTED FROM SERVER:', data); 
    spark.write('receive '+data) 
    }); 

}); 

server.listen(5431); 
console.log("Server has started listening"); 

그리고 나는 그것을 테스트 방법 : 위의 명령에서

$ wscat -c http://localhost:5431/ws 
connected (press CTRL+C to quit) 
< "Herro Client, I am Server" 
> hello 
> 

당신이 때 요청 연결을 클라이언트가 메시지를받을 수 있음을 알 수는 아래 프리머스 코드입니다. 하지만 서버에 'hello'를 보내면 클라이언트는 서버로부터 피드백 메시지를받지 못합니다. 그리고 서버는 'hello'메시지도 출력하지 않습니다. 내 코드에 문제가 있습니까? spark.on('data', function(data) 메서드는 아무 효과가없는 것 같습니다.

답변

0

유효한 JSON 데이터를 서버에 보내지 않아 스파크 오류가 발생했습니다.

메시지 : '들어오는 데이터를 디코딩하지 못했습니다 위치에 JSON 에 예기치 않은 토큰 a를 0'

이 시도 :

http = require('http'); 
server = http.createServer(); 

Primus = require('primus'); 
primus = new Primus(server, { 
    transformer: 'websockets', 
    pathname: 'ws' 
}); 


primus.on('initialised', function() { 
    console.log('Primus Initialized.'); 
}); 

primus.on('connection', function connection(spark) { 
    console.log("client has connected"); 

    spark.write("Herro Client, I am Server"); 

    spark.on('data', function(data) { 
    console.log('PRINTED FROM SERVER:', data); 
    spark.write('received'); 
    }); 

    spark.on('heartbeat', function() { 
    console.log('hearbeat...'); 
    }); 


    //happens after primus.disconnection 
    spark.on('end', function() { 
    console.log('spark end'); 
    }); 

    spark.on('error', function (v) { 
    console.log('spark error', v); 
    }); 

}); 

//happens before spark.end 
primus.on('disconnection', function (spark) { 
    console.log('primus disconnection'); 
}); 

primus.on('error', function error(err) { 
    console.log('primus error', err.stack); 
}); 

server.listen(5431); 
다음과 같이 그것은 나를 위해 일한

:

$ wscat -c 127.0.0.1:5431/ws/websocket 
connected (press CTRL+C to quit) 
< "Herro Client, I am Server" 
> {"a":"b"} 
< "received" 
> {"valid":"json"} 
< "received" 
관련 문제