⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 serverlistener.java

📁 Bluetooth chat Server and Client in j2me
💻 JAVA
字号:
/* I BlueTooth You -- Simple BlueTooth talker Copyright (C) 2007 Jan Tomka, Martin Vysny This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details. */package net.sf.btw.ibtu.bluetooth;import java.io.DataInputStream;import java.io.IOException;import net.sf.btw.btlib.IServerListener;import net.sf.btw.btlib.Server;import net.sf.btw.ibtu.Message;import net.sf.btw.ibtu.ui.HistoryCanvas;import net.sf.btw.tools.Logger;/** * Listens for server events and acts accordingly. *  * @author Martin Vysny *  */public final class ServerListener implements IServerListener {	/**	 * Reference to the {@link HistoryCanvas} to append system and user	 * messages to.	 */	private final HistoryCanvas canvas;	/**	 * Instance of server this listener handles events for.	 */	public Server server;	/**	 * Creates new listener.	 * 	 * @param canvas	 *            canvas that stores messages	 */	public ServerListener(HistoryCanvas canvas) {		super();		this.canvas = canvas;	}	/**	 * Handles event of new client connecting. Broadcasts the system	 * message notifying existing clients about new client joining. Then	 * sends new client five most recent history messages.	 *	 * @param id	 *            ID number of new client.	 * @param name	 *            Device name of new client.	 * 	 * @see net.sf.btw.btlib.IServerListener#clientConnected(int,	 *      java.lang.String)	 */	public void clientConnected(int id, String name) {                final byte idb;                int count = 5;		int msgCount = canvas.messages.size();		int firstMsgIndex = 0;		for (int i = msgCount - 1; i >= 0; i--) {			final Message msg = (Message) canvas.messages.elementAt(i);			if (msg.isSystemMessage())				continue;			count--;			if (count == 0) {				firstMsgIndex = i;				break;			}		}		for (int i = firstMsgIndex; i < msgCount; i++) {			final Message msg = (Message) canvas.messages.elementAt(i);			if (!msg.isSystemMessage())				server.sendBuffer((byte)id, msg.toByteArray());		}				/* Broadcast join info to clients, including the new one. */		broadcast(new Message(null, name + " has joined"), -1);	}	/**	 * Sends a message to all clients except one. The one client excepted	 * is usually a sender of a message. Message gets appended to the	 * server's history canvas.	 *	 * @param message	 *            Message to be broadcasted.	 * @param exceptClientId	 *            ID number of a client to be excluded.	 */	private void broadcast(final Message message, final int exceptClientId) {		canvas.append(message);		server.sendBuffer(server.getClientIDs().keys(), (byte)exceptClientId, message				.toByteArray());	}	/**	 * Handles a client disconnection event. Broadcasts a system message	 * informing clients about the one disconnected.	 * 	 * @param id	 *            ID number of a client disconnected.	 * @param name	 *            Device name of a client disconnected.	 *	 * @see net.sf.btw.btlib.IServerListener#clientDisconnected(int,	 *      java.lang.String)	 */	public void clientDisconnected(int id, String name) {		broadcast(new Message(null, name + " has quit"), id);	}	/**	 * Handles a message that arrived to server. Reads a message and	 * broadcasts it to all clients except the one message came from. In	 * case of any error, server sends an error message to the originating	 * client.	 *	 * @param clientID	 *            ID number of a client the message came from.	 * @param name	 *            Unused.	 * @param message	 *            Unused.	 * @param messageLength	 *            Unused.	 * @param stream	 *            Input stream the message is to be read from.	 * 	 * @see net.sf.btw.btlib.IServerListener#messageArrived(int,	 *      java.lang.String, byte[], int, java.io.DataInputStream)	 */	public void messageArrived(int clientID, String name, byte[] message,			int messageLength, DataInputStream stream) {		// send the message to all clients		try {			final Message msg = Message.fromStream(stream);			broadcast(msg, clientID);		} catch (IOException ex) {			Logger.error("Failed to decode message", ex);			//server.sendBuffer(clientID, new Message(null,			//		"Error receiving message").toByteArray());			return;		}	}	/**	 * Handles an error that occured on a server side. If an error occured	 * while waiting for connection, no action is performed. Otherwise,	 * append a system message to the history canvas and display the error	 * alert.	 *	 * @param clientID	 *            ID number of a client the communication with caused the	 *            error.	 * @param errorHint	 *            Specific identification of an error.	 * @param ex	 *            Exception containing more information about the error	 *            that occured.	 * 	 * @see net.sf.btw.btlib.IErrorListener#errorOccured(int, int,	 *      java.lang.Exception)	 */	public void errorOccured(int clientID, int errorHint, boolean listenerError, Exception ex) {		if (errorHint != ERROR_HINT_WAITING_FOR_CONNECTION)			return;		canvas.append(new Message(null, "Error occured: " + ex));	}    public void clientConnected(final byte id, final String name) {    }    public void clientDisconnected(final byte id, final String name) {    }    public void messageArrived(final byte clientID, final String name, byte[] message, int messageLength, DataInputStream stream) {    }    public void errorOccured(final byte peerId, final int errorHint, final boolean listenerError, final Exception ex) {    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -