简体   繁体   English

如何在TCP套接字连接会话中保存数据?

[英]How to save data in TCP socket connection session?

I want to code a server in java which will accept the information from many devices and store the information in database. 我想用Java编写一个服务器,它将接受来自许多设备的信息并将信息存储在数据库中。 The devices will keep sending the packets. 设备将继续发送数据包。 The first packet will contain the unique deviceId, and after that only data related to the device. 第一个数据包将包含唯一的deviceId,此后仅包含与设备相关的数据。 I want to save data along with deviceId. 我想与deviceId一起保存数据。 Up to now, I could develop a multithreaded server which can server many clients. 到现在为止,我可以开发一个可以为许多客户端提供服务的多线程服务器。 But when I get data, I either loose deviceId or gets wrong deviceId. 但是,当我获取数据时,我要么松散了deviceId要么得到了错误的deviceId。 Can anybody help? 有人可以帮忙吗?

Thanks in advance. 提前致谢。

Java is not my best field of coding but i hope these ideas will help. Java不是我最好的编码领域,但我希望这些想法会有所帮助。

The database accessing can be done with hibernate or some other OR-Mappe, so you can manipulate your database like an object. 可以使用休眠或其他OR-Mappe完成数据库访问,因此您可以像处理对象一样操作数据库。 For the information in the packets you can send the information when you successfully connected to the server like: 对于数据包中的信息,您可以在成功连接到服务器后发送信息,例如:

public void connect(string servername)
{
  ConnectionMethod();
  if(connected)
  {
    SendObject(/*Enter information here*/);
  }
}

Then in the receiving thread you could check for a certain class of the incoming message and handle it accordingly, like store it in the database or something like this. 然后,在接收线程中,您可以检查传入消息的特定类别并进行相应处理,例如将其存储在数据库中或类似的内容。 For the wrong device ID you have to check if you are in the correct thread when you get the packets 对于错误的设备ID,您必须在获取数据包时检查是否处于正确的线程中

如果要开发无状态协议,则必须向每个设备(例如HTTP会话)发送ID,并且设备必须与服务器提供的SessionID连接。

If you are using the one-thread-per-connection pattern, you can keep the deviceId as a field of your thread objects, and pass it to each method it calls, or you can store the deviceid in a ThreadLocal: 如果使用每个连接一个线程的模式,则可以将deviceId保留为线程对象的字段,并将其传递给它调用的每个方法,或者可以将deviceid存储在ThreadLocal中:

private static ThreadLocal<String> deviceId = new ThreadLocal<String>();

public static String getDeviceId() {
    return deviceId.get();
}

public static void setDeviceId(String newValue) {
    deviceId.set(newValue);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM