直接在本地通過socket進(jìn)行通信。node.js作為服務(wù)器,java向node.js請求消息,node.js處理請求并返回。
以下部分測試通過,之后就可以在這個基礎(chǔ)上編寫后續(xù)的代碼了。
由于使用了readLine()函數(shù),所以java發(fā)送或接收的數(shù)據(jù)都需要保證有換行符。所以臨時在node.js發(fā)送語句加了換行符,后期可以考慮用緩沖區(qū)。
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);