简体   繁体   中英

Client side tcp with node.js/socket.io?

I'm new to node.js/socket.io so I don't really know what I'm doing, but I've got this for my server side:

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


var server = app.createServer(function (socket) {
  socket.write("Echo server\r\n");
  socket.pipe(socket);
  socket.on('data', function(data) {
    console.log(data);
  });
});

var io = require('socket.io').listen(server)

server.listen(81);

So the tcp server works when I use nc localhost 81 and send it data. However, I don't know how to connect and send data to the tcp server on a website from the server side using script tags. So what would the client side be to connect to this tcp server and send data to it?

Thanks!

Newly added code:

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);

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');

alert('here');



</script>

What happened:

I have a webpage loading which takes one socket and a nc localhost 81 which takes up another socket. So the nc displays everything the web page sends. After I connect the webpage, the alert('here'); is executed and the nc shows the http request, however, nothing else is sent to the tcp server, and the webpage is in constant refresh status. Why does the webpage never fully load, the 'hi' messages never get sent, and what about the http request to a tcp server? Why doesn't my tcp client fail with my tcp server?

Socket.io's how to use page shows you exactly how to do that.

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost/');
  socket.on('connect', function () {
    socket.send('hi');

    socket.on('message', function (msg) {
      // my msg
    });
  });
</script>

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