我对java还不熟悉,所以还在想办法。我按照一个指南来创建一个聊天应用程序,但是由于某些原因,serverworker中bufferedreader的readline()并没有按它应该的方式运行。我从来没有机会在终端写任何东西,因为它似乎只是暂停。看了其他类似的问题,并没有真正得到答案,所以任何帮助都是值得的。
主要内容:
public class ServerMain {
public static void main(String[] args) {
int port = 8818;
try {
ServerSocket serverSocket = new ServerSocket(port);
while(true) {
System.out.println("About to accept client connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from " + clientSocket);
ServerWorker worker = new ServerWorker(clientSocket);
worker.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务器工作者:
public class ServerWorker extends Thread {
private final Socket clientSocket;
public ServerWorker(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try {
handleClientSocket();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void handleClientSocket() throws IOException, InterruptedException {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ( (line = reader.readLine()) != null) {
if ("quit".equalsIgnoreCase(line)) {
break;
}
String msg = "You typed: " + line + "\n";
outputStream.write(msg.getBytes());
}
clientSocket.close();
}
}
暂无答案!
目前还没有任何答案,快来回答吧!