我有幾個關於我的服務器端代碼的問題。由於我不知道如何調試服務器端代碼,我在這裏問它可能是什麼原因。在我的for(;;)
循環,如果信息來了nullfor循環休息之前來到我的if(msg==null)
聲明,所以我不能播出它可能是什麼問題?由於java-serverside for(;;)循環在readline()爲null時停止
public class ChatServer {
String gonderen1;
String alan1;
private static final int PORT_NUMBER = 8000;
Map<String, List<PrintWriter>> clients;
List<PrintWriter> clientwriter;
ArrayList<String> liste = new ArrayList<String>();
/** Creates a new server. */
public ChatServer() {
clients = new HashMap<String, List<PrintWriter>>();
clientwriter = new LinkedList<PrintWriter>();
}
/** Starts the server. */
public void start() {
try {
ServerSocket s = new ServerSocket(PORT_NUMBER);
for (;;) {
Socket incoming = s.accept();
new ClientHandler(incoming).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/** Adds a new client identified by the given print writer. */
private void addClient(PrintWriter out,String alan) {
synchronized(clientwriter) {
clientwriter.add(out);
clients.put(alan, clientwriter);
}
}
/** Adds the client with given print writer. */
private void removeClient(PrintWriter out) {
synchronized(clientwriter) {
clientwriter.remove(out);
clients.remove(alan1);
}
}
private void broadcast(String msg,String alan) {
for(PrintWriter out : clients.get(alan)){
out.println(msg);
out.flush();
}
}
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(USAGE);
System.exit(-1);
}
new ChatServer().start();
}
private class ClientHandler extends Thread {
private Socket incoming;
public ClientHandler(Socket incoming) {
this.incoming = incoming;
}
public void run() {
PrintWriter out = null;
try {
out = new PrintWriter(
new OutputStreamWriter(incoming.getOutputStream()));
// inform the server of this new client
/* ChatServer.this.addClient(out,"mert");
out.print("Welcome to AndyChat! mert");
out.println("Enter BYE to exit.");
out.flush();*/
BufferedReader in
= new BufferedReader(
new InputStreamReader(incoming.getInputStream()));
String msg;
for(;;) {
msg = in.readLine();
if(msg!=null){
liste.add(msg);
Pattern pat = Pattern.compile("<Gonderen>(.*?)</Gonderen>");
Matcher mat = pat.matcher(msg);
if (mat.find()) {
gonderen1 = mat.group(1).replaceAll("\\s",""); // => "3"
System.out.println("Gonderen "+gonderen1);
}
Pattern p = Pattern.compile("<Alan>(.*?)</Alan>");
Matcher m = p.matcher(msg);
if (m.find()) {
alan1 = m.group(1).replaceAll("\\s",""); // => "3"
out.print("dsa");
System.out.println("Alanin adi "+alan1);
}
if(alan1!=null){
System.out.println(clients.get("mert"));
ChatServer.this.addClient(out,alan1);
}
} else {
for(int i =0;i<liste.size();i++){
ChatServer.this.broadcast(msg,"mert");
System.out.println("null gelmedi");}
break;
}
}
incoming.close();
ChatServer.this.removeClient(out);
} catch (Exception e) {
if (out != null) {
ChatServer.this.removeClient(out);
}
e.printStackTrace();
}
}
}
}
它可能不會中斷。它從來沒有使如果陳述,因爲新行尚未收到.. – 2014-10-05 10:45:10
我看到,但我能做些什麼來使它接收? @KorayTugay – mert 2014-10-05 11:31:44
嘗試讀取方法,而不是readLine。你爲什麼不知道如何調試服務器? – 2014-10-05 11:35:59