我尝试在Eclipse中使用Tomcat运行此代码,但我没有得到客户端服务器的任何输出。我应该在项目中包含一些libriries(jar文件,js文件......)吗?谢谢。
这里有两个文件:
<html>
<body onload ="registerSSE()" >
<script>
function registerSSE()
{
alert('test 1');
var source = new EventSource('http://localhost:8080/hello/sse');
alert('Test2');
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};
/*source.addEventListener('server-time',function (e){
alert('ea');
},true);*/
}
</script>
<output id ="result"></output>
</body>
</html>
servlet:
import java.io.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class sse extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
System.out.println("SSE Demo");
response.setContentType("text/event-stream");
PrintWriter pw = response.getWriter();
int i=0;
while(true) {
i++;
pw.write("event: server-time\n\n"); //take note of the 2 \n 's, also on the next line.
pw.write("data: "+ i + "\n\n");
System.out.println("Data Sent!!!"+i);
if(i>10)
break;
}
pw.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request,response);
}
}
我需要哪个版本的tomcat?以及我需要哪种连接器类型?
_ WEB.XML _
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>demo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>sse</servlet-name>
<servlet-class>sse</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sse</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
答案 0 :(得分:1)
我不了解EventResource,但据我所知,如果你能够在浏览器中打开资源,它应该会让你领先一步。
在web.xml中进行更改: -
<servlet-class>
使用包名称(例如 - com.test.sse
<url-pattern>
您可以在此处设置/*
,以便它适用于每个网址。进行此更改后,尝试在浏览器中打开资源,看看是否有帮助。