我正在用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