简体   繁体   中英

SSL socket.io client not receiving server response

## Problem : Failed to establish socket connection using SSL between client and server, while simulated client connection success.

Source code placed here on github .

## Client Side

App.js initial connection socket with server.

 // Import Components import React, { Component } from "react"; // vvvvvvvvvvvvvvvvvvvvvvvvvvv // Below same code successfully in Server.js but failed in this client const io = require("socket.io-client"); const ioClient = io.connect("https://localhost:8080", { secure: true, reconnection: true, rejectUnauthorized: false }); ioClient.on("seq-num", (msg) => console.info('Client: ' + msg)); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ class App extends Component { render() { return (<div></div>); } } export default App;

## Server side

Server.js simple server just to create socket for client to connect to

 const expressApp = require("express")() const fs = require("fs") const https = require("https"); const secureServer = https.createServer({ key: fs.readFileSync('./ssl/server.key'), cert: fs.readFileSync('./ssl/server.crt') }, expressApp); const ios = require('socket.io')(secureServer); secureServer.listen(8080, () => { console.log("secure server started at 8080"); }) let sequenceNumberByClient = new Map(); // event fired every time a new client connects: ios.on("connection", (socket) => { console.info(`Client connected [id=${socket.id}]`); // initialize this client's sequence number sequenceNumberByClient.set(socket, 1); // when socket disconnects, remove it from the list: socket.on("disconnect", () => { sequenceNumberByClient.delete(socket); console.info(`Client gone [id=${socket.id}]`); }); }); // sends each client its current sequence number setInterval(() => { for (const [client, sequenceNumber] of sequenceNumberByClient.entries()) { client.emit("seq-num", sequenceNumber); sequenceNumberByClient.set(client, sequenceNumber + 1); } }, 1000); // ###### Simulate Client socket call // Below code failed to connect if placed in client App.js const io = require("socket.io-client"); const ioClient = io.connect("https://localhost:8080", { secure: true, reconnection: true, rejectUnauthorized: false }); ioClient.on("seq-num", (msg) => console.info('Simulated client: ' + msg));

Solution

The code is fine . Just go to https://localhost:8080 (or your server), when browser asked for permission, accept self-signed cert and your client page should now work. Hope this may saves your time.

Explanation

As both client and server run on develop environment and server cert was self-signed, chrome (or other browser) blocked unauthorized ssl cert, ie blocking connection to server on https://localhost:8080 in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM