这里我有一个socket.io服务器,它从节点api和angular客户端获取数据。我用套接字客户端测试了套接字服务器,我可以获取数据。但是当我尝试获取数据时,我也无法获取,也无法发送帖子数据。
注意:我们每次执行请求时都会返回值
下面是我的套接字服务器代码
var socket = io.listen(server);
socket.on('connection', function (client) {
// new client is here!
client.on('getreq', function () {
http.get("http://localhost:3000/book", function (res) {
let data = []
res.on('data', chunk => {
data.push(chunk)
});
res.on('end', () => {
console.log(JSON.parse(data));
client.send(JSON.parse(data));
})
});
});
client.on('posreq', function (postdata) {
request.post('http://localhost:3000/book',{
json: {
postdata
}},(error, res, body)=>{
if (error) {
console.error(error)
return
}
console.log(`statusCode: ${res.statusCode}`)
console.log(body)
client.send(body)
}
)
});
client.on('disconnect', function () {
console.log('connection closed');
});
});
角度代码: service.ts
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
observable: Observable<any>;
public socketUrl = "http://localhost:4000";
socket;
constructor() {
this.socket = io(this.socketUrl);
}
getData():Observable<any>{
return this.observable = new Observable((observer) =>
this.socket.emit('getreq', (data) => observer.next(data))
);
}
组件代码:
title = 'web-client';
constructor(public sock:SocketIoService){
}
ngOnInit() {
this.sock.getData().subscribe(res => {
console.log(res);
console.log('got data')
});
}
我如何将这些方法包括在我的节点客户端中?
var socket = require('socket.io-client')('http://localhost:4000');
socket.connect();
socket.emit("getreq");
socket.emit("posreq",JSON.stringify({ "title": "max"}));
socket.on('connect', function(){
console.log('connected');
socket.send('hi!');
});
socket.on('message', function(data){
console.log('message recived: ' + JSON.stringify(data));
});
socket.on('disconnect', function(){
console.log('disconected');
});