简体   繁体   English

Java Socket 在开始接收客户端请求时消耗 100% CPU

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

I have a Socket that consumes 100% CPU, Single client always sends the data to server around 4096 bytes, at the server side I want to get client data & convert into actual form & store into database.我有一个消耗 100% CPU 的套接字,单个客户端总是将数据发送到服务器大约 4096 字节,在服务器端我想获取客户端数据并转换为实际形式并存储到数据库中。 Client sending data after every 3 Seconds.客户端每 3 秒发送一次数据。 I did the following code to get client request.我做了以下代码来获取客户请求。

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

Client code written in C so datatypes are different than Java because of that I need to convert received bytes into actual form & insert into database.客户端代码用 C 编写,因此数据类型与 Java 不同,因为我需要将接收到的字节转换为实际形式并插入数据库。 Thread class code as per follows:螺纹 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();
    }
}

try it as follow:尝试如下:

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