[英]how to properly save and retrieve threads into/fom mongodb database in java?
我有一个由一台服务器和多个客户端设备组成的局域网。 设备的配置方式使它们永久尝试连接到侦听定义明确的端口(例如端口号4000)的服务器(因此在客户端,所有设置都已设置)。
这是系统的逐步工作方式:
-在启动时,服务器接受所有尝试连接的客户端设备(为每个连接创建一个客户端套接字)。
-服务器创建一个线程,稍后在必要时与客户端进行进一步通信。
-服务器将创建的线程与关联的套接字保存到mongodb数据库中。
-将为所有连接的客户端设备完成此操作
稍后,当有一条命令要发送给选定的客户端设备(通过GUI)时,
-服务器端应首先连接到数据库,并使用关联的客户端套接字检索为该特定客户端创建的线程。
-然后服务器应启动检索到的线程。
-最后,在启动的线程中,应创建一个输入/输出流,以便将命令写入客户端套接字并读取答案(将进行进一步处理)。
这就是我实现多线程服务器类的方式:
import java.net.*;
import java.util.Arrays;
import java.util.Set;
import com.mongodb.*;
import java.io.*;
public class MultiThreadedServer {
public static void main(String[] args) throws IOException {
// variables's declaration
int portNumber = 4000;
boolean listening = true;
QuoteServerThread thr = null;
Socket clientSocket = null;
MongoClient mongoClient = null;
try {
//Creates a server socket listening on port 4000
ServerSocket serverSocket = new ServerSocket(portNumber);
//set the socket timeout
serverSocket.setSoTimeout(1000);
while (listening ) {
//Accepts a client
clientSocket = serverSocket.accept();
// Creates thread
thr = new ClientServerThread(clientSocket);
//Access the database and saves the thread
mongoClient = new MongoClient();
DB db = mongoClient.getDB( "testingDB" );
DBCollection collection = db.getCollection("testData");
//This is how I though of saving the thread in the DB. I don't know if its the proper way though
// I would also like ot save it with the associate client socket for later use
BasicDBObject doc = new BasicDBObject();
doc.put("threadID", thr.getId());
collection.insert(doc);
}
//Here I would like to access the database and and get the thread with the associated client socket and start the thread
// I don't know how to do it !!!!
} catch (IOException e) {
System.out.println(e);
}
mongoClient.close();
serverSocket.close();
}
这是线程类:
import java.net.*;
import java.io.*;
public class ClientServerThread extends Thread {
private Socket socket = null;
public ClientServerThread(Socket socket) {
super("ClientServerThread");
this.socket = socket;
}
@Override
public void run() {
try{
// Get the client socket, create input and output streams and send command to the client device.
.........
.........
}catch(Exception e){
e.printStackTrace();
}
}
}
我的问题是我不知道:
-使用相关的客户端套接字将创建的线程保存到mongodb数据库的正确方法。 -如何从数据库检索线程。
我真的被困在这里,如果有人可以帮助我,我将不胜感激。
提前致谢 !!
您无法将线程或套接字保存到数据库中。
即使在最好的情况下,您也只能保存它们的某种表示形式(线程名称,套接字地址和端口)。 您将无法加载它们并使它们再次“运行”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.