首页>代码>javascript websocket实现的简单聊天程序>/reverse_ajax/src/com/cn/test/chapter2/websocket/Endpoint.java
package com.cn.test.chapter2.websocket;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.codehaus.jettison.json.JSONArray;
import org.eclipse.jetty.websocket.WebSocket;

/**
 * @author Mathieu Carbou (mathieu.carbou@gmail.com)
 */
class Endpoint implements WebSocket.OnTextMessage  {

	protected Connection _connection;
	
	private Endpoints endpoints;
	
	private static int clientCounter = 0;
    private int clientId = clientCounter++;
	
	public Endpoint(Endpoints endpoints) {
		this.setEndpoints(endpoints);
	}
	
	@Override
	public void onClose(int code, String message) {
		this.endpoints.remove(this);
	}

	@Override
	public void onOpen(Connection connection) {
		_connection = connection;
		try {
			this._connection.sendMessage(new JSONArray().put("ClientID = " + clientId).toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        endpoints.offer(this);
	}
	
	/**
	 * 发送信息
	 * @param data
	 */
	public void sendMessage(Endpoint fromEndpoint, String data){
		try {
			if(this._connection != null && this._connection.isOpen()){
				if(fromEndpoint.clientId == 0){
					this._connection.sendMessage(new JSONArray().put("FROM[系统广播]  : " + data).toString());
				}else{
					this._connection.sendMessage(new JSONArray().put("FROM " + fromEndpoint.clientId + " : " + data).toString());
				}
			}else{
				this._connection.disconnect();
				endpoints.remove(this);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			this._connection.disconnect();
		}
	}

	@Override
	public void onMessage(final String data) {
		this.endpoints.broadcast(this,data);
	}

	public Endpoints getEndpoints() {
		return endpoints;
	}

	public void setEndpoints(Endpoints endpoints) {
		this.endpoints = endpoints;
	}
	
	


}
最近下载更多
xiaoding1999  LV7 2020年12月22日
0101010323  LV2 2020年9月5日
gaoxin222  LV14 2020年8月23日
wukunhua  LV2 2020年7月22日
huhuhu525354  LV1 2020年7月15日
t88525  LV1 2020年5月13日
浙雨扬  LV10 2019年11月25日
Swl_124  LV2 2019年11月4日
kangdi  LV10 2019年10月28日
skipple3  LV39 2019年10月15日
最近浏览更多
zeng1206  LV5 2023年12月21日
hxy19991216  LV4 2023年12月20日
1234567p  LV1 2023年12月4日
edpwyg  LV14 2023年11月4日
gann2015  LV24 2023年9月17日
yybb7435100  LV2 2023年8月7日
高腾达  LV3 2023年5月22日
zhiwei0127  LV1 2022年12月14日
GuoGuoX 2022年12月9日
暂无贡献等级
lioyiphy 2022年9月19日
暂无贡献等级
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友