问题
I am using net module to connect client with my server. And here is my code.
const Net = require('net');
client = Net.connect(parseInt(port), host, function() {
console.log('server connected')
})
console.log("ooooooooooooooooooooooooooooo")
client.on('data', function(chunk) {
let data = chunk.toString()
console.log(data)
});
client.on('error', function(error) {
console.error('error', error);
});
The issue is when I connect it with single client it doesn't give me data inside client.on('data'
but when I connect it will two or more clients it gets connected and I am getting my data. Someone pls help.
If there any other module I can use ?
回答1:
I have three Java TCP servers each running on their own thread, this particular one handles localhost connections from the NodeJS server which is mainly TEXT or JSON objects. It will read a command and respond.
The NodeJS server then sends that data back to the client browser using socket.io
.
/*
* Handle the nodejs interaction on localhost port 2000
*/
public class DeviceServer3 extends Thread {
private static DeviceServer dev_server = null;
private boolean quit = false;
private final int port = 2000;
public DeviceServer3(DeviceServer server) {
dev_server = server; // store original server
}
public void quitSignal() { // safely shutdown thread
System.out.println("WLMedia Node Java Server exiting...");
quit = true;
while (dev_server.thread_count.get() != 0) {
try { Thread.sleep(5);
} catch (InterruptedException ex) {}
}
}
@Override
public void run() { // main thread
ServerSocket listen_socket = null;
while (!quit) {
try {
listen_socket = new ServerSocket(port);
//listen_socket.setSoTimeout(5000);
listen_socket.setReuseAddress(true);
while (!quit) {
Socket connection = listen_socket.accept();
checkSocket(connection);
}
} catch (IOException e) {
System.out.println("Node Server catch: " + e.getLocalizedMessage());
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
}
} finally {
try {
if (listen_socket != null) {
listen_socket.close();
}
} catch (IOException e) {
System.out.println("server finally: " + e.getMessage());
}
}
}
}
private void checkSocket(Socket socket) {
// Only allow 'localhost' connections
if (socket.getInetAddress().isLoopbackAddress()) {
handleSocket(socket); // TODO change to a thread
} else {
System.out.println("WARNING: Outside connection attempt from: "
+ socket.getInetAddress().toString());
}
try {
socket.close();
System.out.println("Port 2000 socket disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
private BufferedReader getBufferedReader(Socket socket)
throws IOException {
InputStreamReader is = new InputStreamReader(socket.getInputStream());
return new BufferedReader(is);
}
private BufferedWriter getBufferedWriter(Socket socket)
throws IOException {
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
return new BufferedWriter(os);
}
// Safely here to handle the socket connection
private void handleSocket(Socket socket) {
System.out.println("Port 2000 socket connected");
try {
BufferedReader br = getBufferedReader(socket);
BufferedWriter bw = getBufferedWriter(socket);
String command = br.readLine();
switch (command) {
/* Media Manager */
case "media_areas":
System.out.println("NodeJS media_areas");
get_media_areas(br, bw);
break;
case "media_categories":
System.out.println("NodeJS media_categories");
get_media_categories(br, bw);
break;
/* Device manager */
case "devices_get":
System.out.println("NodeJS get_devices");
get_devices(br, bw);
break;
default:
System.out.println("NodeJS command not recognised: " + command);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Handle commands
*/
// Command: media_areas
private void get_media_areas(BufferedReader br, BufferedWriter bw)
throws IOException {
JSONArray area_list = new JSONArray(); // create JSON array
System.out.println("Getting Area list");
synchronized (dev_server.library.media_lock) {
for (Area area : dev_server.library.media) {
area_list.put(area.name);
System.out.println("Area: " + area.name);
}
}
bw.write(area_list.toString()); // send JSON array back to NodeJS server
bw.flush(); // ensure a flush before the socket is closed
}
// ...
The issue I had was the data not being sent to the Node server, which using the flush()
fixed that issue before the socket was closed.
This is a snipped from the Node server which connects to the Java TCP server and then sends the JSON data back to the clients browser.
const global = require("../global/global.js");
const login = require("../login/login");
const node_port = 2000;
const host = "localhost";
function m_get_media_areas(socket) {
// check user logged in (return to login page)
if (!login.check_logged_in(socket)) { return; }
client = new global.net.Socket(); // connect to Java TCP server
client.connect({port: node_port, host: host}, () =>
{ client.write("media_areas\n"); });
// send the JSON string to clients browser over socket.io
client.on("data", (data) => { socket.emit("media_areas", data); });
client.on("end", () => {});
client.on("error", () => { console.log("ERROR: getting areas"); });
}
module.exports = {
get_media_areas : m_get_media_areas,
// ...
}
On the clients browser side I just use socket.io
to emit the command and then just listent for the event so that I can use the data.
// get area list
socket.emit("media_areas");
// media variables
media_area = "";
media_category = "";
media_videos = {}; // a JSON array of JSON objects
socket.on("media_areas", (res) => {
json = JSON.parse(new TextDecoder().decode(res));
$("#list_media_area").empty();
$("#list_media_category").empty();
$("#list_media_videos").empty();
json.forEach(area => {
if (area !== null && area !== "")
$("#list_media_area").append("<li>" + area);
});
media_area = "";
$("#list_media_area li").click(function() {
$(this).addClass("li_selected").siblings().removeClass("li_selected");
media_area = $(this).text();
console.log("Media Area Selected: " + media_area);
$("#accordion_video_category").click();
socket.emit("media_categories", {"area": media_area});
});
});
That's how I've managed to get around it and it works for me great.
The Java JSON library I used is: https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22
回答2:
Without more information on your server implementation it is difficult to answer this question directly. Here is a general example that should be helpful for you.
server.js
const net = require('net');
net.createServer(function(socket) {
// listen for data from the client
socket.on('data', function(data) {
console.log('data from client: ', String(data));
});
// write data to the client
socket.write('hello from the server\n');
}).listen('3000', function() {
console.log('server listening on 3000');
});
client.js
const net = require('net');
const socket = net.connect(3000, 'localhost')
// listen for data from the server
socket.on('data', function(data) {
console.log('data from server: ', String(data));
});
// write data to the server
socket.write('hello from the client\n');
First run node server.js
then from a separate tab run node client.js
. You should see the communication between the server and client. Another tool that may be helpful for you is telnet
, which provides a simple tcp interface. You can test your server by using telnet localhost 3000
来源:https://stackoverflow.com/questions/64820201/client-on-not-getting-data-on-single-connect