我正在尝试在离子电容器(基于角度的应用程序)中实现 socket-io-client,但无法将客户端连接到服务器。
这是我使用的应用内模块的套接字服务。
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {environment} from '../environments/environment'
@Injectable({
providedIn: 'root'
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {environment} from '../environments/environment'
@Injectable({
providedIn: 'root'
})
export class SocketioService {
socket:any;
constructor() {
this.socket = io('http://localhost:5000',{ transports : ['websocket'] });
console.log("socket",this.socket)
}
setupSocketConnection() {
console.log("socketio from socket service")
this.socket = io(environment.SOCKET_ENDPOINT);
console.log("socket",this.socket)
this.socket.emit('my message', 'Hello there from Angular.');
this.socket.on("test",(arg)=>{
console.log(arg)
})
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
这是我尝试在客户端控制套接字时得到的
import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import {environment} from '../environments/environment'
@Injectable({
providedIn: 'root'
})
export class SocketioService {
socket:any;
constructor() {
this.socket = io('http://localhost:5000',{ transports : ['websocket'] });
console.log("socket",this.socket)
}
setupSocketConnection() {
console.log("socketio from socket service")
this.socket = io(environment.SOCKET_ENDPOINT);
console.log("socket",this.socket)
this.socket.emit('my message', 'Hello there from Angular.');
this.socket.on("test",(arg)=>{
console.log(arg)
})
}
}
答案 0 :(得分:0)
您应该为客户端使用 ngx-socket-io Library,而不是使用 socket.io-client
库。
在您的 app.module.ts
内
导入方式:
import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://localhost:8081', options: {} };
@NgModule({
...
imports: [
...
SocketIoModule.forRoot(config),
...
],
..
})