試圖編寫一個簡單的服務器來回顯文本,需要給它多個線程。每當客戶端連接時,我都會收到一個套接字。我不太清楚最新的錯誤,我只是剛剛開始學習,所以我不懂。如果任何人都可以告訴我什麼是錯的,我會很感激。 注意:這段代碼顯然不是完全完成的,我大多隻需要解決上述問題。閉合插座問題
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
public final class EchoServer
{
public static void main(String[] args) throws Exception
{
try (ServerSocket serverSocket = new ServerSocket(22222))
{
while (true)
{
try (Socket socket = serverSocket.accept())
{
Thread newThread = new Thread(new server(socket));
newThread.start();
}
}
}
}
}
class server implements Runnable
{
Socket mySocket;
server(Socket s)
{
mySocket = s;
}
public void run()
{
//while(true)
//{
try
{
System.out.println("Client connected ");
InputStream is = mySocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
OutputStream os = mySocket.getOutputStream();
PrintStream out = new PrintStream(os);
String input = ("...");
while(!input.equals("exit"))
{
input = br.readLine();
out.println("Server> " + input);
}
}
catch(IOException e)
{
System.out.println(e);
}
//}
}
}
你應該閱讀,直到'br.readLine()'返回'null' –