您的位置:首頁技術文章
文章詳情頁

node.js - node socket出錯,這是什么原因?另外我想設置連接超時,怎么寫呢?

瀏覽:193日期:2024-08-04 09:35:41

問題描述

node.js - node socket出錯,這是什么原因?另外我想設置連接超時,怎么寫呢?

node.js - node socket出錯,這是什么原因?另外我想設置連接超時,怎么寫呢?

問題解答

回答1:

1.client.connetc第二參數43表示什么????, client.connect只接收兩個參數(第二個可選) socket.connect(options[, connectListener])

client.connect(server, function(){ console.log(’connected successfully’);})

2.我想知道你的server傳進來是啥值 可以是{ port: 8888, host: ’localhost’ }或者{ path: ’/xxx/tt.sock’}

3.設置超時,直接設置timeout即可,詳細見下面的代碼,但是你要清楚,即使超時了,只是會出發一個timeout的event,socket連接不會關閉的,必須手動關閉(調用end(),或者destory())。

4.沒看到你服務端的代碼,還有客戶端調用的代碼,我寫了一個例子 你自己看看

考慮你版本問題,我盡量采用ES5的寫法server.js

var net = require(’net’)var server = net.createServer(function(socket) { socket.end(’goodbyen’)}).on(’error’, function(err) { // handle errors here throw err});// listen on localhost:8888.server.listen({ host: ’localhost’, port: 8888}, function() { console.log(’opened server on’, server.address())});

client.js

var net = require(’net’)var output = ’’var client = new net.Socket();client.connect({ port: 8888, host: ’localhost’}, function() { console.log(’connetc to server successfully’)})//設置超時方法client.setTimeout(3000) //設置3s超時client.on(’timeout’, function() { console.log(’timeout for client’)})client.on(’data’, function(data) { output = data.toString() client.end();})

国产综合久久一区二区三区