while
ループをスレッドに入れるにはどうすればよいですか?
public class Weather {
public static void main(String[] args) throws UnknownHostException, IOException {
String host = "rainmaker.wunderground.com";
int port = 3000;
int byteOfData;
{
try (Socket socket = new Socket(host, port);
InputStream inputStream = socket.getInputStream();
OutputStream ouputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
//also, a thread for reading from stdin
Thread remoteOutputStream = new Thread() {
@Override
public void run() {
//while loop should go here
// java.net.SocketException: Socket closed
//why does this error occur?
}
};
remoteOutputStream.start();
while ((byteOfData = inputStream.read()) != -1) { //put into thread
out.print((char) byteOfData);
}
}
}
}
}
while
ループをスレッドに入れるjava.net.SocketException: Socket closed
と、おそらく how が原因でスローされますtry with resources works
。しかし、この種の試行でスレッドを使用する方法がわかりません。
複数のスレッドが存在するtry
ため、1 つはローカルの InputStream を読み取るため、もう 1 つはリモートの OutputStream を読み取るためです。