当前位置:主页 > 查看内容

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

发布时间:2021-05-27 00:00| 位朋友查看

简介:step1、为项目安装依赖 在终端输入以下命令为我们的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": "……

step1、为项目安装依赖

在终端输入以下命令为我们的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",

step2、编写后台服务

可以在项目中新建一个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....');
})

step3、创建angular服务

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、创建组件

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文件引入

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

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

到此这篇关于在Angular项目使用socket.io实现通信的文章就介绍到这了,更多相关Angular使用socket.io实现通信内容请搜索站长技术以前的文章或继续浏览下面的相关文章希望大家以后多多支持站长技术!


原文链接:https://m.jb51.net/article/203495.htm
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:marquee元素实现滚动字体图片滑动等效果 下一篇:没有了

推荐图文


随机推荐