You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中使用Socket.io?附代码求助

在Angular中使用Socket.io的正确姿势

看起来你把Node.js服务器端的代码直接写到Angular组件里啦,这可不行哦——Angular是前端框架,Socket.io的服务器端代码得单独放在Node.js项目中,前端用socket.io-client来连接它。我来一步步教你怎么弄:

第一步:搭建Socket.io服务器(单独的Node.js项目)

先创建一个新的文件夹作为服务器端项目,然后初始化并安装依赖:

mkdir socket-server
cd socket-server
npm init -y
npm install express socket.io cors

然后创建server.js文件,写入服务器代码:

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');

const app = express();
app.use(cors()); // 处理跨域,允许Angular项目访问

const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "http://localhost:4200", // 你的Angular项目地址
    methods: ["GET", "POST"]
  }
});

// 监听客户端连接
io.on('connection', (socket) => {
  console.log('用户已连接:', socket.id);

  // 监听客户端发送的消息
  socket.on('send_message', (data) => {
    console.log('收到消息:', data);
    // 把消息广播给所有客户端
    io.emit('receive_message', data);
  });

  // 监听客户端断开连接
  socket.on('disconnect', () => {
    console.log('用户已断开连接:', socket.id);
  });
});

const PORT = 8080;
server.listen(PORT, () => {
  console.log(`服务器运行在http://localhost:${PORT}`);
});

启动服务器:

node server.js

第二步:在Angular项目中配置Socket.io客户端

回到你的Angular项目,安装socket.io-client:

npm install socket.io-client

然后创建一个Socket服务(推荐用Angular服务来封装Socket.io,方便全局使用):

ng generate service socket

在socket.service.ts中写入:

import { Injectable } from '@angular/core';
import { io, Socket } from 'socket.io-client';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SocketService {
  private socket: Socket;
  private readonly SERVER_URL = 'http://localhost:8080'; // 对应你的Socket服务器地址

  constructor() {
    this.socket = io(this.SERVER_URL);
  }

  // 发送消息到服务器
  sendMessage(message: string) {
    this.socket.emit('send_message', message);
  }

  // 监听服务器发来的消息
  onReceiveMessage(): Observable<string> {
    return new Observable((observer) => {
      this.socket.on('receive_message', (data) => {
        observer.next(data);
      });
    });
  }

  // 断开连接
  disconnect() {
    if (this.socket) {
      this.socket.disconnect();
    }
  }
}

第三步:在Angular组件中使用Socket服务

修改你的app.component.ts,去掉原来的服务器代码,换成使用Socket服务:

import { Component, OnDestroy } from '@angular/core';
import { SocketService } from './socket.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnDestroy {
  message = '';
  receivedMessages: string[] = [];
  private messageSubscription: Subscription;

  constructor(private socketService: SocketService) {
    // 订阅服务器发来的消息
    this.messageSubscription = this.socketService.onReceiveMessage().subscribe((data) => {
      this.receivedMessages.push(data);
    });
  }

  sendMessage() {
    if (this.message.trim()) {
      this.socketService.sendMessage(this.message);
      this.message = '';
    }
  }

  ngOnDestroy() {
    // 组件销毁时取消订阅,断开连接
    if (this.messageSubscription) {
      this.messageSubscription.unsubscribe();
    }
    this.socketService.disconnect();
  }
}

然后在app.component.html中添加简单的UI:

<div>
  <input type="text" [(ngModel)]="message" placeholder="输入消息">
  <button (click)="sendMessage()">发送</button>
</div>

<div>
  <h3>收到的消息:</h3>
  <ul>
    <li *ngFor="let msg of receivedMessages">{{ msg }}</li>
  </ul>
</div>

关键注意事项

  • 确保服务器和Angular项目的端口正确,跨域配置要对应(如果Angular不是跑在4200,要修改服务器的cors.origin)
  • 记得在Angular模块中导入FormsModule(因为用了ngModel),在app.module.ts中添加:
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // ...其他导入
    FormsModule
  ]
})

这样就能在Angular中正常使用Socket.io实现实时通信啦!

内容的提问来源于stack exchange,提问作者Adil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:49:26