【发布时间】:2014-12-21 13:32:41
【问题描述】:
我正在使用聊天服务器客户端完成我的任务。这是我如何启动服务器
public static void StartServer(){
// Create socket
try {
serversocket = new ServerSocket(ServerPort);
} catch (Exception e) {
isError = true;
ERRORCODE = "ERROR! Cannot create a new socket! " + e.getMessage();
return;
}
// A new thread to wait for connection
Thread TH_Wait4Connection = new Thread(){
public void run(){
while(true){
String ERRORHere = "-1"; // To specify whre the Errors are
try {
Connection = new Socket();
Connection = serversocket.accept();
} catch (Exception e) {
ERRORCODE = ERRORHere + " : " + e.getMessage();
return;
}
// Another Thread to handle a connection
try {
ERRORHere = "1";
Thread Client = new Thread(new ConnHandler(Connection));
ERRORHere = "2";
threadList.add(Client);
ERRORHere = "3";
Client.start();
ERRORHere = "4";
} catch (Exception e) {
ERRORCODE = ERRORHere + " : " + e.getMessage();
return;
}
try {Thread.sleep(10);} catch (Exception e) {}
} // End why loop
} // End run()
};
TH_Wait4Connection.start();
}
当我在 Eclipse 中调试时,我的客户端可以连接到服务器并且一切正常,服务器创建线程并且没有捕获到异常。但是如果我运行,它会进入最后一个捕获和我的错误代码
ERRORCODE = ERRORHere + " : " + e.getMessage();
是
1 : 6 > 4
这些错误是什么?以及如何解决?
感谢阅读。
更新类 ConnHandler
public class ConnHandler implements Runnable{
public ConnHandler(Socket Connection) throws Exception{
InputStream IS = Connection.getInputStream();
byte[] InData = new byte[1024];
int bytesCount = IS.read(InData);
// Remove first 6 bytes
byte[] NewInData = Arrays.copyOfRange(InData, 6, bytesCount);
}
public void run(){}
}
【问题讨论】:
-
ConnHandler 类做了什么,我认为基于“1”然后它在从 ConnHandler 实例化时崩溃,对吧?
-
感谢您的回复。 ConnHandler 已更新。我不知道我的代码哪里出了问题,我想这个类很简单。它只是在运行应用程序时崩溃,当我运行调试时没有任何反应。
-
哎呀,我想我找到了我的问题。我尝试删除这一行 byte[] NewInData = Arrays.copyOfRange(InData, 6, bytesCount); bytesCount 超出 InData 数组范围。但我想知道为什么我运行调试时没有错误。非常感谢!
标签: java eclipse sockets server