我正在使用 Chat Server-client 完成我的任务。这是我如何启动服务器
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(){}
}