webSocket输出乱码,求指点

西夏一品堂 发布于 2015/06/06 16:30
阅读 2K+
收藏 0

代码如下:

@ServerEndpoint("/cmd/prog")
public class Progress
{
	@OnMessage
	public void onMessage(String msg, Session session) throws Exception
	{
		for(int i=0;i<=10;i++)
		{
			String tmp = "让我们定义一个 Java EE websocket服务器端" + i;
			System.out.println("send msg : " + tmp);
			session.getBasicRemote().sendText(tmp);
			TimeUnit.SECONDS.sleep(1l);
		}
	}
	
	@OnOpen
	public void onOpen()
	{
		System.out.println("------------onOpen------------");
	}
	
	@OnClose
	public void onClose()
	{
		System.out.println("------------onClose------------");
	}
}



JSP代码:


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>进度提示</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<style type="text/css">
	.list {
		color:red;
		height: 20px;
	}
</style>
</head>
<body>
<h1>进度测试</h1>
<button onclick="start()">开始</button>
<div id="messages"></div>
<script type="text/javascript">

	var webSocket = null;
	
	function init()
	{
		webSocket = new WebSocket('ws://127.0.0.1:10000/cmd/prog');
		
		webSocket.onerror = function(event) 
		{
		  onError(event)
		};
		
		webSocket.onopen = function(event) 
		{
		  onOpen(event)
		};
		
		webSocket.onmessage = function(event)
		{
		  onMessage(event)
		};
	}
	
	function onMessage(event)
	{
	  	var html = $('#messages').html();
	  	$('#messages').html(html + '<div class="list">'+event.data+'</div>');
	}
	
	function start()
	{
		webSocket.send(null);
	}
	
	function onOpen(event) 
	{

	}
	
	function onError(event) 
	{
	  	alert(event.data);
	}
	
	$(function(){
		init();
	});
</script>
</body>
</html>



页面输出结果为:

maven项目,配置的是jetty容器

<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.2.11.v20150529</version>
				<configuration>
					<stopKey>foo</stopKey>
					<stopPort>9999</stopPort>
					<httpConnector>
						<port>10000</port>
					</httpConnector>
					<webApp>
						<contextPath>/</contextPath>
					</webApp>
				</configuration>
			</plugin>



运行命令为:

mvn jetty:run


文件的保存格式为UTF-8

请问,为什么有乱码?

加载中
0
k
klx502
请问最后怎么解决了?
0
蓝色蒲公英2015
蓝色蒲公英2015
请问最后怎么解决了?
返回顶部
顶部