简体   繁体   中英

How to connect to tcp server via node.js/socket.io from client?

I've set up a tcp server using node.js/socket.io, but I can't figure out how to connect to it via the client side. I've tried the client code from http://socket.io/#how-to-use but it sends a http request to a tcp server and after the connection is made, the webpage does not finish loading the the loading circle continues to move. I can tell from other sockets that the http request sends all the headers to the tcp server, but I don't think the connection is established as the webpage never fully loads and I can't pass anything else to the tcp server. How do you establish the client side of the webpage to a tcp server?

My client:

<script type="text/javascript" src="http://localhost:82/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:81');

socket.on('connect', function () {
    socket.send('hi');
});

socket.send('hi1');
socket.emit('hi2');
</script>

My Server:

var app = require('net')
  , fs = require('fs')

var sockets_list = [];

var server = app.createServer(function (socket) {
  sockets_list.push(socket);
  socket.write("Echo server\r\n");

  socket.on('data', function(data) {
    console.log(data);
    for (var i = 0; i < sockets_list.length; i++) {
        sockets_list[i].write(data);
    }

  });

  socket.on('end', function() {
    var i = sockets_list.indexOf(socket);
    sockets_list.splice(i, 1);
  });

});

server.listen(81);

Needless to say, the 'hi' messages never reach the tcp server.

I suppose this is Cross Domain Request problem. You load your page from localhost:82 but make request to localhost:81.

A bit late to the party, and also my very first answer on stackoverflow.

I ran into the same problem when I initially started working with socket.io. The problem is with the server side code, you're not requiring the socket.io module:

var io = require('socket.io');

io.on('connection',function(socket){
    console.log('socket connected successfully');

    socket.on('data',function(data){
        console.log('data',data);
    });
}

Then once the server is up and running, you request the script 'socket.io/socket.io.js' from it:

<script type="text/javascript" src="http://localhost:81/socket.io/socket.io.js">

I don't believe you can mix/match the core 'net' module of nodejs with the client-side libraries of socket.io.

Hope this helps.

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