无法创建从HTML到localhost的套接字连接

时间:2018-03-07 07:46:46

标签: javascript html node.js sockets

我正在尝试在HTML文件(我从笔记本电脑打开)到同一台笔记本电脑上运行的套接字服务器之间创建套接字连接。 要启动服务器,我使用以下代码:

var net = require('net');

var server = net.createServer();  
server.on('connection', handleConnection);

server.listen(9000, function() {  
    console.log('server listening to %j', server.address());
});

function handleConnection(conn) {  
  var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;
  console.log('new client connection from %s', remoteAddress);

  conn.on('data', onConnData);
  conn.once('close', onConnClose);
  conn.on('error', onConnError);

  function onConnData(d) {
      var chunks = [];
      chunks.push(d);
      console.log('Client at  %s  says %s', remoteAddress, Buffer.concat(chunks).toString());
      conn.write(d);
  }

  function onConnClose() {
    console.log('connection from %s closed', remoteAddress);
  }

  function onConnError(err) {
    console.log('Connection %s error: %s', remoteAddress, err.message);
  }

}

当我尝试使用简单的Java应用程序连接到服务器时,它运行得很好,这是Java应用程序的代码:

public class simpleClient {
    public static void main(String[] args){
        simpleClient sC = new simpleClient();
        sC.connect();
    }

    @SuppressWarnings("resource")
    public void connect (){
        DataOutputStream out = null;
        DataInputStream in = null;
        Socket s = null;

        SocketAddress sockaddr = new InetSocketAddress("127.0.0.1", 9000);
        s = new Socket();
        try {
            s.connect(sockaddr, 10 * 1000);
            s.setSoTimeout(30000);
            out = new DataOutputStream (s.getOutputStream());
            in = new DataInputStream (s.getInputStream());


            String str = "Aloha my friend.";
            out.write(str.getBytes());
            out.flush();
        } 
        catch (IOException e) {e.printStackTrace();}    
    }
}

连接成功后服务器登录:

server listening to {"address":"::","family":"IPv6","port":9000}
new client connection from ::ffff:127.0.0.1:54669
Client at  ::ffff:127.0.0.1:54669  says Aloha my friend.
Connection ::ffff:127.0.0.1:54669 error: read ECONNRESET
connection from ::ffff:127.0.0.1:54669 closed

但是,当我尝试使用HTML文件中的脚本连接到服务器时,没有任何反应。我无法建立连接。

我最接近连接的是使用以下HTML脚本:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="ISO-8859-1">
        <title>Insert title here</title>
    </head>
    <body>
        <script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
        <script>
        function sendData() {
            try {
                var socket = io.connect('http://localhost:9000');
                socket.on('connect', function(data) {
                    socket.emit('Hello.');
                    socket.on('message', function (msg) {
                        socket.emit('some message ...');
                    });
                });
            }
            catch(err) {
                alert('ERROR: socket.io encountered a problem:\n\n' + err);
            }
        }
sendData();
        </script>
    </body>
    </html>

并且服务器端的日志看起来像这样:

    server listening to {"address":"::","family":"IPv6","port":9000}
    new client connection from ::1:65397
Client at  ::1:65397  says GET /socket.io/?EIO=2&transport=polling&t=1520412442267-4 HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7
connection from ::1:65397 closed

我真的迷失在这里,因为我不熟悉JavaScript / HTML领域,所以我真的不知道该寻找什么以及如何解决它。

问题是:HTML端的套接字客户端的最佳/最简单实现是什么,这将允许我向/从服务器发送和接收数据?

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:0)

socket.emit方法至少需要两个参数,事件名称和实际数据。您目前正在发出一个只有一个名称(“Hello。”)但没有数据的事件。

因为在后端,你正在侦听名为“data”的事件,所以这应该有效:

socket.emit('data', 'Hello.');