gpt4 book ai didi

javascript - client.on 没有在单次连接上获取数据

转载 作者:行者123 更新时间:2023-12-03 07:03:54 25 4
gpt4 key购买 nike

我正在使用 net将客户端与我的服务器连接的模块。这是我的代码。

        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);
});

问题是当我将它与单个客户端连接时它不会在 client.on('data' 中给我数据但是当我连接它时它会连接两个或多个客户端并且我正在获取我的数据。请有人帮忙。

如果有任何其他模块我可以使用?

最佳答案

我有三个 Java TCP 服务器,每个都在自己的线程上运行,这个特定的服务器处理来自 NodeJS 服务器的本地主机连接,该服务器主要是 TEXT 或 JSON 对象。它将读取命令并响应。

然后 NodeJS 服务器使用 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
}

// ...

我遇到的问题是数据没有发送到 Node 服务器,它使用 flush() 在套接字关闭之前解决了这个问题。

这是从连接到 Java TCP 服务器的 Node 服务器截取的,然后将 JSON 数据发送回客户端浏览器。

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,
// ...
}

在客户端浏览器端,我只使用 socket.io 发出命令,然后只监听事件以便我可以使用数据。

// 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});
});
});

这就是我设法绕过它的方法,它对我非常有用。

我使用的 Java JSON 库是: https://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22

关于javascript - client.on 没有在单次连接上获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64820201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com