我正在尝试学习如何使用套接字,我写了一个小型的echo服务器。我在eclipse上运行代码,然后我转到命令提示符并telnet到端口,它应该回显,但它给了我这个错误:
Exception in thread "Thread-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 20
at java.lang.String.getChars(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at echoserver.run(echoserver.java:40)
这是我的代码:
public final class echoserver extends Thread {
private static final int PORT = 8889;
public static void main(String args[]){
echoserver Echoserver = new echoserver();
if (Echoserver != null){
Echoserver.start();
}
}
public void run (){
try {
ServerSocket server = new ServerSocket(PORT , 1);
while (true) {
Socket client =server.accept();
System.out.println("Client connected");
while (true){
BufferedReader reader =
new BufferedReader(new InputStreamReader(
client.getInputStream()));
System.out.println("Read from client");
String textLine = reader.readLine() + "\n";
if (textLine.equalsIgnoreCase("Exit\n")){
System.out.println("exit invoked, closing client");
break;
}
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(
client.getOutputStream()));
System.out.println("Echo input to client");
writer.write("echo from server:"
+ textLine, 0 , textLine.length() + 18);
writer.flush();
}
client.close();
}
} catch(IOException e){
System.err.println(e);
}
}
}
我该如何解决此错误?
答案 0 :(得分:3)
这是问题所在:
writer.write("echo from server:" + textLine, 0 , textLine.length() + 18);
您的“额外文字”实际上是 17 个字符,而不是18个。您不需要指定偏移和长度 - 您可以使用:
writer.write("echo from server:" + textLine);