首页 > 代码库 > nodejs使用tcp协议编程(nodejs服务器端,java客户端)

nodejs使用tcp协议编程(nodejs服务器端,java客户端)

var net = require ('net');
var HOST = '192.168.1.50';
var PORT = 8809;
net.createServer(function(sock){
        console.log('CONNECTED:'+sock.remoteAddress + ":"+ sock.remotePort);

        sock.on('data',function(data){
        console.log('DATA'+sock.remoteAddress +":" +data);
        sock.write('You said "'+data+'"');
        });
        sock.on('close',function(data){
                console.log('CLOSED:'+sock.remoteAddress +''+sock.remotePort);
        });
}).listen(PORT,HOST);
console.log('Server listening on '+HOST+':'+PORT);



public static void main(String[] args) throws Exception, IOException {
		Socket socket = new Socket("192.168.1.50", 8809);
		BufferedReader sin = new BufferedReader(
				new InputStreamReader(System.in));
		PrintWriter os = new PrintWriter(socket.getOutputStream());
		BufferedReader is = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));
		String readline;
		readline = sin.readLine();
		while (!readline.equals("bye")) {
			os.println(readline);
			os.flush();
			System.out.println("Client:" + readline);
			System.out.println("Server:" + is.readLine());
			readline = sin.readLine();
		}
		os.close();
		is.close();
		socket.close();
	}