我已经实现了一个套接字侦听器来读取从 GPS 发送的数据,但它消耗了我 90% 的 CPU。我知道这是我的代码造成的,但我看不到在哪里。
这是我的主要课程:
public class PortToDB {
ServerSocket serverSocket = null;
public void listenSocket(){
try{
serverSocket = new ServerSocket(50000);
} catch (IOException e) {
System.out.println("Could not listen on port 50000. " + e);
System.exit(-1);
}
while(true){
GPSData gd;
try{
gd = new GPSData(serverSocket.accept());
Thread t = new Thread(gd);
t.start();
} catch (IOException e) {
System.out.println("Accept failed: 50000. " + e);
System.exit(-1);
}
}
}
public static void main(String[] args) {
PortToDB portToDb = new PortToDB();
portToDb.listenSocket();
}
}
这是我的可运行类:
class GPSData implements Runnable {
private Socket client;
DBHandler dbhandler = new DBHandler();
GPSData(Socket client) { this.client = client; }
public void run(){
String line;
BufferedReader in = null;
try{
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException e) {
System.out.println("in or out failed");
System.exit(-1);
}
while(true){
try{
if((line = in.readLine()) != null){
dbhandler.dbInsert(line);
}
} catch (IOException e) {
System.out.println("Read failed");
System.exit(-1);
}
}
}
}