gpt4 book ai didi

java - 套接字不保存列表中的值

转载 作者:行者123 更新时间:2023-12-02 04:35:13 24 4
gpt4 key购买 nike

我是用 Java 进行网络开发的新手,我想创建一个简单的 Socket 服务器,它从客户端获取值并将所有值收集到 ArrayList 中。我编写了一个示例代码,但在服务器端它不收集字符串。这是我的服务器端:

服务器

public class ServerSideSocket extends Thread{
private ServerSocket serverSocket;
private Socket socket;
private ArrayList<String> list = new ArrayList<String>();
DataInputStream inData;
DataOutputStream outData;

public ServerSideSocket(int port) throws IOException {
serverSocket = new ServerSocket(port);
}

public void run() {
while(true) {
try{
System.out.println("Waiting for connection...");
socket = serverSocket.accept();
System.out.println("Connected!" );
inData = new DataInputStream(socket.getInputStream());
outData = new DataOutputStream(socket.getOutputStream());

System.out.println(inData.readUTF());

list.add(inData.readUTF());

System.out.println("------------ VALUES ---------");
for (String value: list) {
System.out.println(value);
}
System.out.println("------------ END VALUES ---------");

outData.writeUTF("Message saved!");
outData.flush();
} catch (SocketException ex) {
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inData.close();
outData.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String[] args) {
int port = 9999;
try {
Thread t = new ServerSideSocket(port);
t.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}

}

客户:

public class ClientSideSocket {
public static void main(String[] args) {
String serverName = "localhost";
int port = 9999;
String line = "";

try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream out = client.getOutputStream();
DataOutputStream outData = new DataOutputStream(out);
InputStream in = client.getInputStream();
DataInputStream inData = new DataInputStream(in);

outData.writeUTF("Simple text");
outData.flush();
System.out.println("Response from server: " + inData.readUTF());
System.out.println("You can write more messages!");
System.out.println();

client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

我的代码有什么问题吗?

最佳答案

发生这种情况是因为您尝试通过调用 inData.readUTF() 方法从数据流中读取两次。第一次调用成功从流中读取数据,但您没有保存结果,而是尝试执行下面的另一次读取 2 行。readUTF() 是阻塞方法,因此它等待永远不会来自同一客户端的另一部分数据。这就是为什么你的服务器永远挂起

您想要做的是读取一次并将结果存储到局部变量中:

String res = inData.readUTF();
list.add(res);

关于java - 套接字不保存列表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30910886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com