1
我是Nodejs的新手,並試圖使用套接字設置服務器客戶端連接。以下是我的代碼。服務器工作正常,但客戶端未連接。 請任何人都可以幫我弄清楚這個錯誤。節點js中的客戶端代碼
,不勝感謝 JESSI
Server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
io.on('data', function(data) {
console.log('DATA from client is: ' + data);
// Close the client socket completely
});
server.listen(4200);
console.log('Monitoring server listening on port 4200');
Client.js
var HOST = '127.0.0.1';
var PORT = 4200;
var express = require('express');
var app = express();
var client = require('http').createServer(app);
var io = require('socket.io')(client);
client.connect(PORT, HOST, function()
{
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected,
// the server will receive it as message from the client
io.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
非常感謝您的幫助。 –
@JessiAnnGeorge沒問題。只要確保將其標記爲答案,如果它確實可以幫助您,以便其他人知道這是未來查看此問題時的答案。 – peteb
我必須實現的是需要彼此交談的2臺服務器(一個配置和監視服務器)。我不知道如何做到這一點,所以我做了一個作爲服務器,另一個作爲客戶端,並以這種方式說話。客戶端將從配置服務器請求服務,對於soem請求,配置服務器需要從監視服務器獲取數據。我們如何使用2臺服務器來實現這個目標?謝謝 –