前言
nodejs编程中,有时我们希望通过tcpip与外界进行通信,Json数据格式是常见的一种,下面我们将介绍一种简单的接收JSON字符串的方法。
jslet net = require('net'); let port = 8090; let chunk = ""; const startDelimiter = '{'; const endDelimiter = '}'; let startFlag =0; let endFlag =0; let start_index =0; let end_index =0; let server = net.createServer(function handleEvent(socket){ socket.on('data', function(data) { console.log('Recv:::'+data); if(startFlag == 0){ data = data.toString(); let indexStart = data.indexOf(startDelimiter); start_index = getStrCount(data,startDelimiter); end_index = getStrCount(data,endDelimiter); if(indexStart>=0){ data = data.substring(indexStart); let indexEnd = data.lastIndexOf(endDelimiter); if(start_index>end_index){ startFlag =1; }else if(start_index == end_index){ endFlag =1; data = data.substring(0,indexEnd+1); console.log('json 字符串输出:::'+data); }else{ console.log("Get Data Format Error"); chunk = ""; data =""; } }else{ data =""; } }else{ chunk+= data; start_index += getStrCount(chunk,startDelimiter); end_index += getStrCount(chunk,endDelimiter); if(start_index == end_index){ endFlag =1; chunk = chunk.substring(0,indexEnd+1); console.log('Output2:::'+chunk); } } }); }); server.listen(port,function() { console.log('server is listening'); }); function getStrCount(aStr,aChar){ let regex = new RegExp(aChar, 'g'); let result = aStr.match(regex); let count=!result ? 0 : result.length; return count; }
客户端发送标准json字符串
服务器接收JSON字符串情况
注
容错处理还没完成,比如一个json字符串分两次发送,后续有时间更新一下,目前只接收一整段完整的JSON字符串