簡體   English   中英

Java Socket 在開始接收客戶端請求時消耗 100% CPU

[英]Java Socket consumes 100% CPU when started receiving client request

我有一個消耗 100% CPU 的套接字,單個客戶端總是將數據發送到服務器大約 4096 字節,在服務器端我想獲取客戶端數據並轉換為實際形式並存儲到數據庫中。 客戶端每 3 秒發送一次數據。 我做了以下代碼來獲取客戶請求。

    ServerSocket waiting = new ServerSocket(18800, 50, InetAddress.getByName("192.20.50.102"));
    while(true) {
       Socket socket = waiting.accept(); 
       new SessionHandler(socket).start();
    }

客戶端代碼用 C 編寫,因此數據類型與 Java 不同,因為我需要將接收到的字節轉換為實際形式並插入數據庫。 螺紋 class 代碼如下:

public class SessionHandler extends Thread {

private Socket socket;

public SessionHandler(Socket socket) {
    this.socket = socket;
}

public void run() {
    DataInputStream dataInputStream;
    try {
        dataInputStream = new DataInputStream(socket.getInputStream());
        int tcCode = dataInputStream.readInt();
        int length = dataInputStream.readInt();
        if (tcCode == 1001) {
            System.out.println("in 1001");
            byte[] messageByte = new byte[length];
            int totalBytesRead = 0;
            while (totalBytesRead < length) {
                int currentBytesRead = dataInputStream.read(messageByte, totalBytesRead, length - totalBytesRead);
                totalBytesRead = currentBytesRead + totalBytesRead;
            }
            ByteBuffer buffer = ByteBuffer.wrap(messageByte);
            ShortBuffer shortBuffer = buffer.asShortBuffer();
            short[] values = new short[length / 2];
            shortBuffer.get(values);
            TCCodeOneOOOne tcCodeOneOOOne = new TCCodeOneOOOne(values);
            tcCodeOneOOOne.main(null);
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

嘗試如下:

ServerSocket waiting = new ServerSocket(18800, 50, InetAddress.getByName("192.20.50.102"));
Socket socket = waiting.accept(); 
new SessionHandler(socket).start();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM