效果图:
nodejs 服务端:
var net = require('net');
var HOST = '192.168.1.8';
var PORT = 9999;
let server = net.createServer(function(sock) {
console.log('客户端信息: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.setTimeout(3000);
sock.on('connect', function(){
console.log('connect');
})
sock.on('ready', function(){
console.log('ready');
})
sock.on('data', function(data) {
console.log('收到的消息: ' + sock.remoteAddress + ': ' + data);
sock.write('你说: "' + data + '"');
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
sock.on('error', function(err) {
console.log(err);
sock.destroy();
})
sock.on('timeout', function() {
console.log('timeout: '+ sock.remoteAddress + ' ' + sock.remotePort);
sock.destroy();
})
});
server.on('error', (err) => {
console.log(err);
});
now = new Date(new Date().getTime() + 28800000);
console.log(now);
console.log('Server listening on ' + HOST +':'+ PORT);
server.listen(PORT, HOST);
uniapp 客户端:
var Socket = plus.android.importClass("java.net.Socket");
var PrintWriter = plus.android.importClass("java.io.PrintWriter");
var BufferedWriter = plus.android.importClass("java.io.BufferedWriter");
var OutputStreamWriter = plus.android.importClass("java.io.OutputStreamWriter");
var BufferedReader = plus.android.importClass("java.io.BufferedReader");
var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");
var InetSocketAddress = plus.android.importClass("java.net.InetSocketAddress");
var sk = new Socket('192.168.1.8', 9999);
sk.setSoTimeout(5000);
var outputStreamWriter = new OutputStreamWriter(sk.getOutputStream());
var bufferWriter = new BufferedWriter(outputStreamWriter);
var out = new PrintWriter(bufferWriter, true);
out.print('666你好棒');
out.flush();
var inputStreamReader = new InputStreamReader(sk.getInputStream());
var br = new BufferedReader(inputStreamReader);
var msg = br.readLine();
console.log(msg);
以下是用 nodejs编写的客户端:
var net = require('net');
var HOST = '192.168.1.8';
var PORT = 9999;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Chuck Norris!');
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
参考的文档:https://www.dazhuanlan.com/raintwo1/topics/1121328
|