-2
我需要將java中創建的客戶端TCP與使用node.js創建的HTTP服務器連接起來 我希望在點擊完成後我的HTML操作的一個按鈕在客戶端java中通過使用模塊網絡的套接字執行。我需要將java中創建的客戶端TCP與使用node.js創建的HTTP服務器連接
我的HTML代碼:
<body>
<button id="bt1">Button 1</button>
<button id="bt2">Button 2</button>
<button id="bt3">Button 3</button>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('httpServer', function (data) {
console.log(data);
socket.emit('tcp', "For TCP");
});
</script>
</body>
我的代碼Java客戶端:
class ClientSocket{
public static void main(String[] args){
String address = "127.0.0.1";
int port = 5555;
try {
Socket socket = new Socket(address, port);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String ope = in.readLine();
if(ope.equals("1")){
System.out.println("You pulsated on the button 1");
}else if(ope.equals("2")){
System.out.println("You pulsated on the button 2");
}else if(ope.equals("3")){
System.out.println("You pulsated on the button 3");
}
// ........
in.close();
socket.close();
}catch(IOException e){
System.out.println(e);
}
}
}
我的代碼節點serverTCP.js:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 5555;
var server = net.createServer();
server.listen(PORT, HOST);
server.on('connection', function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
sock.write("TCP sending message : 1"); // No send
console.log('Server listening on ' + server.address().address +':'+ server.address().port);
}).listen(PORT, HOST);
我的代碼節點serverHTTP.js:
var http = require('http').createServer(httpHandler), fs = require("fs"), wsock = require('socket.io').listen(http), tcpsock = require('net');
var http_port = 8080;
var tcp_HOST = '127.0.0.1';
var tcp_PORT = 5555;
/**
* http server
*/
function httpHandler (req, res){
fs.readFile(__dirname + '/index.html',
function(err, data) {
if(err){
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
http.listen(http_port);
console.info("HTTP server listening on " + http_port);
wsock.sockets.on('connection', function(socket){
var tcpClient = new tcpsock.Socket({allowHalfOpen: false, readable: true, writable: true});
tcpClient.setEncoding("ascii");
tcpClient.setKeepAlive(true);
tcpClient.connect(tcp_PORT, tcp_HOST, function(){
console.info('CONNECTED TO : ' + tcp_HOST + ':' + tcp_PORT);
tcpClient.on('data', function(data){
console.log('DATA: ' + data);
socket.emit("httpServer", data);
});
tcpClient.on('end', function(data){
console.log('END DATA : ' + data);
});
});
socket.on('tcp-manager', function(message){
console.log('"tcp" : ' + message);
return;
});
socket.emit("httpServer", "Initial Data");
});