gpt4 book ai didi

java - Inputstream.available() 总是返回 0

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:58:00 24 4
gpt4 key购买 nike

我遇到了一些愚蠢的问题,我不知道我做错了什么。

我写了客户端和服务器,客户端工作正常。我检查输出流在客户端是否正常工作有字节,但在服务器中当客户端连接时,方法 in.avable() 返回始终为零?为什么?

我服务器的一些代码:

            try{
serverSocket = new ServerSocket(port);
}
catch (IOException e){
System.err.println("Could not listen on port: " + port);
return false;
}
System.out.println("Server Started");
txtServer.setText("Server wystartował");
return true;
}
else{
txtPort.setText("Brak Portu!");
txtPort.setBorder( BorderFactory.createLineBorder(Color.RED) );
return false;}
}

@Override
public void run() {
try{
clientSocket = serverSocket.accept();
data.clear();

System.out.println("Client connected");
cl_obs = new Client_obs(clientSocket, data);
Thread t = new Thread(cl_obs);
t.start();
}
catch (IOException e){
System.err.println("Accept failed.");
System.exit(1);
}


}
package Server;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class Client_obs implements Runnable {
private InputStream in;
private data data;
private Socket clientSocket = null;
public Client_obs(Socket cl, data data1){
clientSocket =cl;
data = data1;
}
@Override
public void run() {
try {
in = clientSocket.getInputStream();
byte[] data1 = new byte[in.available()];;
for (int i=0; i<data1.length; i++){
data1[i] = (byte)in.read();
}
data.setData(data1);
data.displayMSG(data.getdata());
in.close();
clientSocket.close();

}
catch(IOException e){
e.printStackTrace();
}
}

}

最佳答案

That's a perfectly legal implementation .

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes. Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.

A subclass' implementation of this method may choose to throw an IOException if this input stream has been closed by invoking the close() method.

The available method for class InputStream always returns 0.

关于java - Inputstream.available() 总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14012648/

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