0


我用 Java 编写 UDP 服务器和客户端,以将消息从客户端发送到服务器。就我而言,来自客户端的每条消息都将存储在数据库中。我尝试使用固定线程池制作多线程 UDP 服务器。但是现在我遇到了一个问题,我发现来自客户端的一条消息可以由多个线程处理。我的服务器看起来像这样:

    DatagramSocket serverSocket = new DatagramSocket(9876);
    Map<String, Integer> retryMap = new ConcurrentHashMap<>();
    byte[] receiveData = new byte[1024];

    ExecutorService executor = Executors.newFixedThreadPool(2);

    while(true){
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        serverSocket.receive(receivePacket);
        executor.execute(new ThreadServer(receivePacket, retryMap));
    }

线程服务器类:

public void run(){
  String temp = new String(packet.getData(), 0, packet.getLength()); 
  long threadId = Thread.currentThread().getId();
  System.out.println("Thread Id = "+threadId+" Message = "+temp);
  // insert message to db
}

我的客户看起来像这样:

public class UDPClient1{
String message;
public UDPClient1(String message){
    this.message = message;
    try{
        byte[] sendData;

        DatagramSocket clientSocket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");

        sendData = message.getBytes("UTF-8");

        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
        clientSocket.send(sendPacket);

        clientSocket.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}

public static void main(String args[]) throws InterruptedException{
    int i = 0;
    while(i < 1000){
        new UDPClient1("T000"+i+"_"+i);
        System.out.println(i);
        i++;
        Thread.sleep(2);
    }
}}

服务器的输出显示有时来自客户端的一条消息将由 2 个线程或更多线程处理。

Thread Id = 18 Routing Id = T000975 09:54:11,759 ERROR LogRoutingFileDaoImpl:59 - AMS - Error insert to database org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO LOG_ROUTING_FILE (ID_ROUTING_FILE, FILE_NM , PATH, TYPES, PROTOCOL, SOURCE_NM, TARGET_NM) VALUES (?,?,?,?,?,?,?)]; ERROR: duplicate key value violates unique constraint "log_routing_file_id_routing_file_key"; nested exception is org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "log_routing_file_id_routing_file_key" 
Thread Id = 9 Routing Id = T000975 09:54:11,759 ERROR LogRoutingFileDaoImpl:59 - AMS - Error insert to database org.springframework.dao.DuplicateKeyException: PreparedStatementCallback; SQL [INSERT INTO LOG_ROUTING_FILE (ID_ROUTING_FILE, FILE_NM , PATH, TYPES, PROTOCOL, SOURCE_NM, TARGET_NM) VALUES (?,?,?,?,?,?,?)]; ERROR: duplicate key value violates unique constraint "log_routing_file_id_routing_file_key"; nested exception is org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "log_routing_file_id_routing_file_key"

消息 T000975 由线程 9 和 18 处理。谁能帮我解决这个问题?:)

4

1 回答 1

2
byte[] receiveData = new byte[1024];

您在DatagramPackets.接收循环内的所有 Move this line 之间共享相同的字节数组。

于 2013-10-21T03:04:28.873 回答