直接在本地通过socket进行通信。node.js作为服务器,java向node.js请求消息,node.js处理请求并返回。
以下部分测试通过,之后就可以在这个基础上编写后续的代码了。
由于使用了readLine()函数,所以java发送或接收的数据都需要保证有换行符。所以临时在node.js发送语句加了换行符,后期可以考虑用缓冲区。
java输出:
node.js输出:
java部分
package javatest; import java.net.Socket; import java.util.Scanner; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class test{ public static void main(String[] arges){ try{ Scanner scan = new Scanner(System.in); Socket socket = new Socket ("127.0.0.1", 11111); BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream())); PrintWriter out = new PrintWriter ( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream ())), true); String str = scan.nextLine(); while(!str.equals("quit")){ out.println(str); System.out.println(in.readLine()); str = scan.nextLine(); } out.println(str); System.out.println(in.readLine()); scan.close(); socket.close(); }catch(Exception e){ System.out.println(e); } } }
var net = require('net'); var HOST = '127.0.0.1'; var PORT = 11111; net.createServer(function(socket) { console.log('connection: ' + socket.remoteAddress + ':' + socket.remotePort); socket.on('data', function(data) { console.log('From client : ' + data); socket.write('From server : successfully received!\n' ); }); socket.on('close', function(data) { console.log('close: ' + socket.remoteAddress + ' ' + socket.remotePort); }); }).listen(PORT, HOST); console.log('Server listening on ' + HOST +':'+ PORT);