java堆空间内存溢出_java - 无限循环导致OutOfMemoryError:Java堆空间 - 堆栈内存溢出...

我正在编写一个聊天应用程序。 我使用while(true)无限循环来允许应用程序不断“监听”通过控制台的用户输入和来自Socket输入。 无限循环显然不是实现此目的的最佳方法-毫不奇怪,仅在程序运行约一分钟后(我的计算机迷就尖叫),我得到了OutOfMemoryError: Java Heap space 。

我的问题是:如果不通过无限循环,如何修改程序以不断(或至少每隔很小的时间间隔,如每秒一次)检查输入源,做出响应,然后返回检查?

代码(带有一些注释)如下:

import java.io.*;

import java.net.*;

public class Main {

public static void main(String[] args) throws IOException, ConnectException {

ServerSocket receiveServerSocket = new ServerSocket(Integer.parseInt(args[0])); // args contains two port numbers

Socket sendSocket;

while(true) { // note - I use the exact same infinite loop strategy here, except in this case an OutOfMemoryError is not thrown

try {

sendSocket = new Socket(InetAddress.getLocalHost(), Integer.parseInt(args[1]));

break;

} catch (ConnectException e) {}

}

DataOutputStream os = new DataOutputStream(sendSocket.getOutputStream());

Socket receiveSocket = receiveServerSocket.accept();

DataInputStream is = new DataInputStream(receiveSocket.getInputStream());

BufferedReader input = new BufferedReader (new InputStreamReader(System.in));

String message;

while(true) { // Here's the infinite loop in question

if(input.ready()) { // "checks" to see if the user has entered text

message = input.readLine(); // responds

os.writeInt(message.getBytes().length);

os.writeBytes(message);

}

if(is.available() > 0) { // checks to see if Socket has received text

byte[] bytes = new byte[is.readInt()]; // responds (Incidentally, this is the specific line where the OutOfMemoryError occurs)

is.read(bytes,0,bytes.length);

System.out.println(new String(bytes,0,bytes.length,"UTF-8"));

}

}

}

}

谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值