【问题标题】:how to flush the buffer in TCP connection如何刷新 TCP 连接中的缓冲区
【发布时间】:2016-01-10 11:07:30
【问题描述】:

您好,我遇到了服务器客户端消息从 Web 客户端传递到 TCP 服务器的问题。每次我重新连接到网页时,我的前 6 条消息都会毫无延迟地通过,而第七条消息需要很多时间,并且第一条消息会再次重复。我认为应该有一些缓冲区处理程序,但我不知道如何启动它。帮我解决这个问题。我的服务器和客户端都在节点套接字中(使用 var net = require('net') )。

【问题讨论】:

  • 您的接收代码有问题。 TCP 不重复数据。
  • 感谢您指出我必须查看的正确位置。即使这有负面影响,您的评论只是让我意识到我没有从我的客户那里返回任何对 ajax 调用的响应。这是一次又一次地运行相同的代码。客户端中的一个 res.send('success') 清除了我的错误。再次感谢你拯救了我的一天......@EJP

标签: node.js tcp tcpclient


【解决方案1】:

我的客户必须为我从网页发出的 ajax 调用发送响应:

          $.ajax({
                    type: 'POST',
                    url: 'http://localhost:3000/client',
                    dataType: "json",
                    contentType: "application/json; charset=UTF-8",
                    data: JSON.stringify({name:data+'\r'}),// this is the data i get from web page
                    done : function(data){
                        console.log('on success', data);
                    },
                    fail : function(error){
                        console.log('on error', error)
                    }
                })

和我的节点客户端

var net = require('net');
var _ = require('lodash');

   router.post('/client', function(req, res) {
       var inputJSON = req.body;
       var HOST = '127.0.0.1';
       var PORT = 5000;
       var client = new net.Socket();
       client.connect(PORT, HOST, function() {

           console.log('CONNECTED TO: ' + HOST + ':' + PORT);
           // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
            _.forEach(inputJSON, function(value,key){
                client.write(value);
                // console.log(value);
             })

        });
    //This is the line i missed in my earlier program the client should respond
    res.send('success')
    });

我正在学习节点。所以你可以用你的 cmets 即兴创作我的代码,这样我就可以更好地改进谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    相关资源
    最近更新 更多