(编辑:jimmy 日期: 2024/12/29 浏览:2)
在终端输入以下命令为我们的angular项目安装express、socket.io、socket.io-client
npm install express socket.io socket.io-client
本人安装的各版本信息如下:
"express": "^4.17.1", "socket.io": "^3.0.4", "socket.io-client": "^3.0.4",
可以在项目中新建一个server文件夹,用来存放我们的后台服务,然后新建文件
const app = require('express')(); const http = require('http').createServer(app); const io = require('socket.io')(http, { cors: { // 处理跨域问题 origin: "http://localhost:4300", // angular项目的启动端口,默认4200,本人项目的启动端口为4300,大家根据自己情况修改 methods: ["GET", "POST"], credentials: true } }); io.on('connection', (socket) => { console.log('user connected'); socket.on('add-message', (message) => { io.emit('message', {type: 'new-message', text: message}); }); }) http.listen(4000, () => { // 后台服务启动端口 console.log('start on 4000....'); })
import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; import { io } from 'socket.io-client'; @Injectable() export class ChatService { private url = 'http://localhost:4000'; // 后台服务端口 private socket: any; sendMessage(message: any) { this.socket.emit('add-message', message); } getMessages(): Observable<any> { return new Observable(observer => { this.socket = io(this.url, {withCredentials: true}); this.socket.on('message', (data) => { observer.next(data); }); return () => { this.socket.disconnect(); } }) } }
这里我们创建了两个方法,sendMessage用于将客户端的信息发送给服务端,getMessages用于建立连接,监听服务端事件并返回一个可观察的对象。
import { Component, OnInit, OnDestroy } from '@angular/core'; import { ChatService } from './chat.service'; @Component({ selector: 'test-chat', template: `<div *ngFor="let message of messages"> {{message.text}} </div> <input [(ngModel)]="message" /> <button (click)="sendMessage()">Send</button>`, providers: [ChatService] // 注入依赖 }) export class TestChatComponent implements OnInit, OnDestroy { messages = []; connection: any; message: any; constructor(private chatService: ChatService) { } sendMessage() { this.chatService.sendMessage(this.message); this.message = ''; } ngOnInit() { this.connection = this.chatService.getMessages() .subscribe(message => { // 组件初始化时订阅信息 this.messages.push(message); }); } ngOnDestroy() { this.connection.unsubscribe(); // 组件销毁取消订阅 } }
这样一个简单的socket通信就完成了,效果图如下:
启动服务
前端页面
如果遇到跨域问题,大概率是没有处理跨域,检查自己的代码和端口号是否正确,详情参考handing-cors
另外,如果遇到(本人遇到了,愣是在网上找了半天依然未果)
POST http://localhost:4000/socket.io/"htmlcode">
import { io } from 'socket.io-client';
在网上看到很多人是这样写的 import * as io from ‘socket.io-client',这种写法在typescript中是会报错的,改成上面的写法即可。