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

如何使用Socket.io连接两个不同端口的Angular聊天支持应用?

Hey there! Since you're new to Socket.io, let's break this down step by step—no jargon overload, promise. The key thing to remember here is that Socket.io works on a client-server model: your two Angular apps (App1 and App2) can't connect directly to each other; they both need to connect to a central Socket.io server that handles routing messages between them.

Step 1: Set Up the Central Socket.io Server

First, we'll create a simple Node.js server to act as the middleman. This is where all messages will pass through.

  1. Create a new folder for your server, then initialize a Node project:

    mkdir socket-server
    cd socket-server
    npm init -y
    
  2. Install the required dependencies:

    npm install express socket.io cors
    
  3. Create a server.js file with this code:

    const express = require('express');
    const http = require('http');
    const { Server } = require('socket.io');
    const cors = require('cors');
    
    const app = express();
    app.use(cors({
      origin: ["http://localhost:4200", "http://localhost:4201"], // Replace with your App1 and App2 URLs
      methods: ["GET", "POST"]
    }));
    
    const server = http.createServer(app);
    const io = new Server(server, {
      cors: {
        origin: ["http://localhost:4200", "http://localhost:4201"],
        methods: ["GET", "POST"]
      }
    });
    
    // Track connected agents (App2 instances) if needed
    let connectedAgents = [];
    
    io.on('connection', (socket) => {
      console.log(`User connected: ${socket.id}`);
    
      // Let's assume App2 sends a "join-agent-room" event when it connects
      socket.on('join-agent-room', () => {
        socket.join('agent-room');
        connectedAgents.push(socket.id);
        console.log(`Agent joined: ${socket.id}`);
      });
    
      // Listen for messages from App1
      socket.on('client-message', (data) => {
        console.log(`Received message from client: ${data}`);
        // Send the message to all connected agents in the agent room
        io.to('agent-room').emit('new-client-message', data);
      });
    
      socket.on('disconnect', () => {
        console.log(`User disconnected: ${socket.id}`);
        connectedAgents = connectedAgents.filter(id => id !== socket.id);
      });
    });
    
    server.listen(3000, () => {
      console.log('Socket.io server running on port 3000');
    });
    
  4. Start the server:

    node server.js
    
Step 2: Configure Socket.io Client in App1 (Client Side)

Now let's set up App1 to send messages to the server.

  1. Install the Socket.io client package in App1:

    cd path/to/app1
    npm install socket.io-client
    
  2. In your chat component (e.g., client-chat.component.ts), add this code:

    import { Component } from '@angular/core';
    import { io, Socket } from 'socket.io-client';
    
    @Component({
      selector: 'app-client-chat',
      templateUrl: './client-chat.component.html',
      styleUrls: ['./client-chat.component.css']
    })
    export class ClientChatComponent {
      private socket: Socket;
      messageInput: string = '';
    
      constructor() {
        // Connect to the Socket.io server
        this.socket = io('http://localhost:3000');
      }
    
      sendMessage() {
        if (this.messageInput.trim()) {
          // Emit a "client-message" event to the server
          this.socket.emit('client-message', this.messageInput);
          this.messageInput = '';
        }
      }
    }
    
  3. Update your component template (client-chat.component.html) to add a message input and send button:

    <input type="text" [(ngModel)]="messageInput" placeholder="Type your message...">
    <button (click)="sendMessage()">Send to Agent</button>
    
Step 3: Configure Socket.io Client in App2 (Agent Side)

Next, set up App2 to receive messages from the server.

  1. Install the Socket.io client package in App2:

    cd path/to/app2
    npm install socket.io-client
    
  2. In your agent chat component (e.g., agent-chat.component.ts), add this code:

    import { Component, NgZone } from '@angular/core';
    import { io, Socket } from 'socket.io-client';
    
    @Component({
      selector: 'app-agent-chat',
      templateUrl: './agent-chat.component.html',
      styleUrls: ['./agent-chat.component.css']
    })
    export class AgentChatComponent {
      private socket: Socket;
      clientMessages: string[] = [];
    
      constructor(private ngZone: NgZone) {
        this.socket = io('http://localhost:3000');
    
        // Join the agent room when the component initializes
        this.socket.emit('join-agent-room');
    
        // Listen for new messages from clients
        this.socket.on('new-client-message', (message) => {
          // Use NgZone to ensure Angular updates the view
          this.ngZone.run(() => {
            this.clientMessages.push(message);
          });
        });
      }
    }
    
  3. Update your component template (agent-chat.component.html) to display incoming messages:

    <h3>Client Messages</h3>
    <div *ngFor="let msg of clientMessages">
      <p>{{ msg }}</p>
    </div>
    
Common Pitfalls & Debugging Tips
  • CORS Errors: Make sure your server's CORS configuration includes the exact URLs (including ports) of your Angular apps. If you're testing locally, http://localhost:4200 and http://localhost:4201 are typical, but adjust to match your actual ports.
  • Version Mismatch: Ensure the socket.io-client version in both Angular apps matches the socket.io version in your server. Mismatched versions can cause connection failures.
  • Angular View Updates: When receiving messages in App2, wrap the view update logic in NgZone.run() (like in the example) to ensure Angular detects the change and updates the template.
  • Debug Connections: Use your browser's DevTools (Network tab) to check if the WebSocket connection to ws://localhost:3000 is established. Also, check the server console for connection/disconnection logs, and the browser console for client-side errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 02:57:38