我是 java.net 的新手,正在尝试制作一个简单的客户端-服务器应用程序。这是服务器代码:
public class Consumer extends Thread{
public Socket s;
int num;
public Consumer(int num, Socket s){
this.num = num;
this.s = s;
setDaemon(true);
setPriority(NORM_PRIORITY);
start();
}
public static void main(String args[]){
try {
int i = 0;
ServerSocket server = new ServerSocket(3128, 0, InetAddress.getByName("localhost"));
System.out.println("server started");
while (true){
new Consumer(i, server.accept());
i++;
}
} catch (Exception e){
}
}
public void run(){
try {
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
byte buf[] = new byte[64*1024];
int r = is.read(buf);
String data = new String(buf, 0, r);
data = "" +num+": " +"\n" + data;
os.write(data.getBytes());
s.close();
} catch (Exception e){
System.out.println("init error: " + e);
}
}
}
当我启动它时 - 没有发生任何不好的事情,但是当我从某个客户端发送 smth 时,我得到以下信息:
init error: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
如何解决?