程序小屋

记录生活中的点滴,分享、学习、创新

文章内容 1623902339

在Angular项目使用socket.io实现通信的方法

step1、为项目安装依赖

在终端输入以下命令为我们的angular项目安装express、socket.io、socket.io-client

1
npm install express socket.io socket.io-client

本人安装的各版本信息如下:

1
2
3
"express": "^4.17.1",
"socket.io": "^3.0.4",
"socket.io-client": "^3.0.4",

step2、编写后台服务

可以在项目中新建一个server文件夹,用来存放我们的后台服务,然后新建文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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....');
})

step3、创建angular服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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用于建立连接,监听服务端事件并返回一个可观察的对象。

step4、创建组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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/?EIO=3&transport=polling&t=NQtz_E3 400 (Bad Request)这类的报错,npm安装socket.io-client(这也是为什么我在文章一开始就安装它),在service.ts文件引入

1
import { io } from 'socket.io-client';

在网上看到很多人是这样写的 import * as io from ‘socket.io-client',这种写法在typescript中是会报错的,改成上面的写法即可。

到此这篇关于在Angular项目使用socket.io实现通信的文章就介绍到这了,更多相关Angular使用socket.io实现通信内容请搜索脚本之家以前的文章


*