我正在用java設計一個聊天服務器。通信是基於Http而不是基於套接字的。在客戶端,我有一個小程序。在服務器端我有一個servlet。爲什麼我的聊天服務器servlet的doPost方法不被調用?
小程序:我創建了一個新線程來偵聽傳入消息(GET方法)。主線程用於發送消息(POST消息)。
局部代碼是:
public void start() {
System.out.println("Creating new thread");
Thread thread = new Thread(this);
thread.start();
}
private String getNewMessage() {
System.out.println("Inside getNewMessage");
String msg = null;
try {
while(msg == null) {
System.out.println("Trying to listen to servlet");
URL servlet = new URL(getCodeBase(), "NewServlet?mode=msg");
URLConnection con = servlet.openConnection();
con.setUseCaches(false);
DataInputStream din = new DataInputStream(new BufferedInputStream(con.getInputStream()));
msg = din.readUTF();
System.out.println("message read :" + msg);
}
} catch (Exception e) {
e.printStackTrace();
}
return msg + "\n";
}
public void run() {
System.out.println("Inside new thread");
while(true) {
System.out.println("inside first while");
String newMsg = getNewMessage();
chatOutput.append(newMsg);
System.out.println("Appended!!");
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String message = chatInput.getText();
chatInput.setText("");
chatOutput.append(message + "\n");
try {
System.out.println("Trying to send msg :" + message);
URL url = new URL(getCodeBase(), "NewServlet");
URLConnection servletConnection = url.openConnection();
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
ObjectOutputStream out = new ObjectOutputStream(servletConnection.getOutputStream());
out.writeObject(message);
out.flush();
out.close();
System.out.println("Message sent!");
} catch (Exception e) {
e.printStackTrace();
}
}
這下一個代碼是從servlet側。它使用Observable接口來識別消息並將消息發送給客戶端。你可以看到我已經包含System.out.println(「Some message」);我們可以看到System.out.println(「Some message」);在一些地方。這只是爲了調試目的。 在Java控制檯,我得到下面的輸出:
創建新的線程
裏面新的線程。第一次在裏面的時候是
。
Inside getNewMessage。
嘗試收聽servlet。
Servlet的一面,我得到在tomcat日誌輸出如下:
裏面的doGet。
裏面的getNextMessage。
AddedObserver。
後,我在applet鍵入消息,併發送,我得到的Java控制檯輸出如下:
試圖發送消息:你DER?
發送的消息!
但在servlet端,我沒有得到任何東西在日誌。 我使用O'Reily Java Servlet編程作爲參考(觀察者接口來自那裏)。但我沒有得到兩個客戶之間的任何聊天通信。從日誌中可以看出,不調用doPOST
方法。 這是什麼原因?
忘記添加壞消息。我可以發送消息,但是我收到了「空」消息(GET方法部分,它監聽其他用戶輸入消息並顯示它們,在這種情況下它顯示「null」)。 – mithun1538 2010-03-24 18:09:21
修正了這一點。用ObjectInputStream替換getNewMessage函數中的「DataInputStream ...」部分...這是因爲applet通過ObjectOutputStream()發送輸入的消息。現在聊天服務器工作順利 – mithun1538 2010-03-24 19:00:54