如何使用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.
First, we'll create a simple Node.js server to act as the middleman. This is where all messages will pass through.
Create a new folder for your server, then initialize a Node project:
mkdir socket-server cd socket-server npm init -yInstall the required dependencies:
npm install express socket.io corsCreate a
server.jsfile 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'); });Start the server:
node server.js
Now let's set up App1 to send messages to the server.
Install the Socket.io client package in App1:
cd path/to/app1 npm install socket.io-clientIn 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 = ''; } } }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>
Next, set up App2 to receive messages from the server.
Install the Socket.io client package in App2:
cd path/to/app2 npm install socket.io-clientIn 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); }); }); } }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>
- 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:4200andhttp://localhost:4201are typical, but adjust to match your actual ports. - Version Mismatch: Ensure the
socket.io-clientversion in both Angular apps matches thesocket.ioversion 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:3000is established. Also, check the server console for connection/disconnection logs, and the browser console for client-side errors.
内容的提问来源于stack exchange,提问作者sunflower

