为什么我写了一个简单的socket服务端,一启动接收客户端就很占CPU了
希望高手们帮忙分析一下,大家有什么想法或者建议都可以分享一下。代码如下:
--------------------编程问答-------------------- 循环里面没见你sleep --------------------编程问答-------------------- private Socket client;
public class Server extends Thread {
/**
* 日志文件对象
*/
public static Logger runLog = LoggerFactory.getLogger("RUN");
private Socket client;
private XMLConfigure configure;
private Map commandMap = null;
public Server(Socket client) {
this.client = client;
init();
}
private void init() {
configure = new XMLConfigure();
commandMap = configure.getMap();
}
public void run() {
try {
begin();
} catch (Exception e) {
runLog.info("【Server】客户端已经退出!");
if (this.client != null) {
try {
this.client.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.client = null;
}
}
}
private void begin() throws IOException {
InputStream input = client.getInputStream();
OutputStream output = client.getOutputStream();
while (true) {
byte[] b = new byte[1024];
int len = input.read(b);
byte[] bc = new byte[len];
for (int i = 0; i < len; i++) {
bc[i] = b[i];
}
String re = new String(bc);
runLog.info("【Server】接收到的客户端信息为:" + re);
if (commandMap.containsKey(re)) {
String value = (String) commandMap.get(re);
runLog.info("【Server】往客户端发送的信息为:" + value);
output.write(value.getBytes());
output.flush();
}else{
runLog.info("【Server】找不到"+re+",重新加载一次配置文件...");
configure = new XMLConfigure();
//重新加载完配置文件后,再做一次判读
if (commandMap.containsKey(re)) {
String value = (String) commandMap.get(re);
runLog.info("【Server】往客户端发送的信息为:" + value);
output.write(value.getBytes());
output.flush();
}else{
String value = (String) commandMap.get("error");
runLog.info("【Server】往客户端发送的信息为:" + value);
output.write(value.getBytes());
output.flush();
}
}
}
}
public static void main(String[] args) {
ServerSocket server = null;
Socket client = null;
try {
XMLConfigure conf = new XMLConfigure();
server = new ServerSocket(conf.getPort());
runLog.info("【Server】服务端已启动...");
while (true) {
client = server.accept();
Server Soserver = new Server(client);
Soserver.start();
}
} catch (Exception e) {
runLog.info("【Server】客户端已经退出!");
if (client != null) {
try {
client.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
client = null;
}
if (server != null) {
try {
server.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
server = null;
}
}
}
}
改为局部变量,你这样用,问题大了去了!
补充:Java , Java SE