Ajax聊天

Posted 非非是

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax聊天相关的知识,希望对你有一定的参考价值。

结构:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>index.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
	var xmlHttp;

	function createXMLHttpRequest() {
		if (window.ActiveXObject) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} else if (window.XMLHttpRequest) {
			xmlHttp = new XMLHttpRequest();
		}
	}

	function firstRead() {
		createXMLHttpRequest();
		xmlHttp.open("post", "servlet/ChatServlet", true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //post 传参必须有form表单和此句
		xmlHttp.onreadystatechange = onReadyState;
		xmlHttp.send(null);
		window.setTimeout(firstRead, 1000);
	}
	
	function sendMsg(){
		createXMLHttpRequest();
		xmlHttp.open("post", "servlet/ChatServlet", true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //post 传参必须有form表单和此句
		xmlHttp.onreadystatechange = onReadyState;
		var chatMsg = document.getElementById("chatInfo");
		xmlHttp.send("chatMsg="+chatMsg.value);
		//document.getElementById("showChat").innerText = chatMsg;
		document.getElementById("chatInfo").value= "";//清空文本框
	}
	
	function onReadyState() { //onreadystatechangem 每次状态改变被调用
	
		if (xmlHttp.readyState == 4){//==4 客户端与服务器交互完成,,, ==200是否传输成功.,
			if(xmlHttp.status == 200){
				//alert("服务器返回: " + xmlHttp.responseText);//responseText 返回服务器数据
				document.getElementById("showChat").innerText = xmlHttp.responseText;
			}
		}
	}
	
	function getKeyCode(){
		if(window.event.keyCode == 13){//回车键
			sendMsg();
		}
	}
</script>
</head>
  
  <body onload="firstRead()" onkeydown="getKeyCode()">
  <form action="" enctype="application/x-www-form-urlencoded">
    This is my HTML page. <br>
    <div>
    	<textarea rows="20" cols="60" id="showChat" readonly="readonly"></textarea><br>
    	<input type="text" id="chatInfo" style="width:300px;height:25px">
    	<input type="button" value=" 发送  " onclick="sendMsg()">
    </div>
    </form>
  </body>
</html>

  ChatServlet

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@SuppressWarnings("serial")
public class ChatServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		String chatMsg = request.getParameter("chatMsg");
		ChatService chatService = ChatService.getChat();
		if(null!=chatMsg && chatMsg.trim().length()>0){
			chatService.addMsg(chatMsg, request.getRemoteAddr());
			String getMsg = chatService.getMsg();
			out.print(getMsg);
		}else{
			String getMsg = chatService.getMsg();
			out.print(getMsg);
		}
	}
}

  ChatService

import java.util.LinkedList;

public class ChatService {
	private static ChatService chat;
	private LinkedList<String> list;
	private ChatService(){}
	
	public static ChatService getChat(){
		if(chat==null){
			chat = new ChatService();
		}
		return chat;
	}
	
	public void addMsg(String Msg,String uname){
		if(list==null){
			list = new LinkedList<String>();
		}
		if(list.size()>10){
			list.removeFirst();
		}
		list.add(uname+"说:"+Msg);
		
	}
	
	public String getMsg(){
		
		String Msg = "";
		if(list!=null){
			for (String str:list) {
				Msg+=(str+"\\n");
			}
		}
		return Msg;
	}
}

  结果截图:

以上是关于Ajax聊天的主要内容,如果未能解决你的问题,请参考以下文章

ajax聊天

AJAX相关JS代码片段和部分浏览器模型

Ajax PHP JavaScript MySQL实现简易的无刷新在线聊天室

Comet反向ajax技术实现客服聊天系统

Ajax实现聊天室

创建用户聊天系统 -(PHP、MySQL、AJAX?)