我有一个用 C# 编写的适用于 Windows 的服务器应用程序。我有一个安卓客户端应用程序。我想在无限循环中从客户端向服务器连续发送数据。正在发送数据,但有时会有严重的延迟。我真的被困住了。这是我的客户端代码:
new Thread(new Runnable() {
public void run() {
Socket socket = null;
PrintWriter out = null;
while(true) {
try {
socket = new Socket(IP, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
知道为什么会有延迟吗?
最佳答案
您的问题是您在 while 循环的每一次迭代中都初始化套接字。
new Thread(new Runnable() {
public void run() {
Socket socket = null;
PrintWriter out = null;
while(true) {
try {
socket = new Socket(IP, PORT);
out = new PrintWriter(socket.getOutputStream(), true);
out.println(msg);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
在循环之外重构它,像这样:
new Thread(new Runnable() {
public void run() {
Socket socket = new Socket(IP, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true) {
try {
out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}).start();
除非这是设计使然,在这种情况下,为什么?
关于java - 套接字编程 : Delay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36691548/