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

📄 peer.java

📁 Bluetooth chat Server and Client in j2me
💻 JAVA
字号:
/* The Bluetooth Library for client-server communication Copyright (C) 2006 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.btlib;import java.io.IOException;import javax.bluetooth.BluetoothStateException;import javax.bluetooth.L2CAPConnection;import javax.bluetooth.LocalDevice;import javax.bluetooth.RemoteDevice;import javax.bluetooth.UUID;import net.sf.btw.tools.Logger;/** * Base class for {@link Client} and {@link Server} nodes. Serves also as a * bluetooth utility class. *  * @author Martin Vysny *  */public class Peer {	/**	 * Local Bluetooth Manager	 */	private volatile static LocalDevice localDevice;	/**	 * Local device name.	 */	private volatile static String deviceName;	/**	 * Initializes the bluetooth subsystem. This method must be called prior	 * using any other classes of the BTLib framework. Just call this method	 * when your application is starting.	 * 	 * @throws BluetoothStateException	 *             if error occurs.	 */	public static synchronized void initializeBluetooth()			throws BluetoothStateException {		// get the device instance		if (localDevice != null)			return;		localDevice = LocalDevice.getLocalDevice();		if (localDevice == null)			throw new BluetoothStateException("Bluetooth unavailable"); //$NON-NLS-1$		// get local name		deviceName = getDevice().getFriendlyName();		if (deviceName == null) {			deviceName = getDevice().getBluetoothAddress();		}		if (deviceName == null) {			deviceName = "unknown"; //$NON-NLS-1$		}		maxPacketSize = parseInt(LocalDevice				.getProperty("bluetooth.l2cap.receiveMTU.max"), "maxPacketSize"); //$NON-NLS-1$ //$NON-NLS-2$		maxConnections = parseInt(LocalDevice				.getProperty("bluetooth.connected.devices.max"), //$NON-NLS-1$				"maxConnections"); //$NON-NLS-1$		Logger.info("Bluetooth initialized on " + deviceName //$NON-NLS-1$				+ ", max. connections=" + maxConnections //$NON-NLS-1$				+ ", max. packet size=" + maxPacketSize, null); //$NON-NLS-1$	}	/**	 * Parses given int and returns it. Returns <code>-1</code> if parse	 * attempt failed.	 * 	 * @param string	 *            the number.	 * @param variableName	 *            the variable name for logging purposes.	 * @return integer value of given string.	 */	private static int parseInt(final String string, final String variableName) {		try {			return Integer.parseInt(string);		} catch (NumberFormatException ex) {			Logger.error(					"Failed to parse '" + string + "' for " + variableName, ex); //$NON-NLS-1$ //$NON-NLS-2$			return -1;		}	}	private static int maxConnections = -1;	private static int maxPacketSize = -1;	/**	 * Returns the local device instance.	 * 	 * @return bluetooth device, never <code>null</code>.	 * @throws IllegalStateException	 *             if {@link #initializeBluetooth()} was not called.	 */	public static LocalDevice getDevice() {		if (localDevice == null)			throw new IllegalStateException(					"Bluetooth was not initialized, use initializeBluetooth()"); //$NON-NLS-1$		return localDevice;	}	/**	 * Creates new peer node instance.	 * 	 * @param server	 *            server ID	 * @param receiveMTU	 *            maximum size of received packet, see	 *            {@link L2CAPConnection#getReceiveMTU()} for details.	 * @param transmitMTU	 *            maximum size of transmitted packet, see	 *            {@link L2CAPConnection#getTransmitMTU()} for details.	 * @param listener	 *            listener for events.	 */	protected Peer(final UUID server, final int receiveMTU,			final int transmitMTU, final IErrorListener listener) {		super();		getDevice();		// okay, bluetooth is initialized.		if (listener == null)			throw new IllegalArgumentException("listener cannot be null"); //$NON-NLS-1$		if ((receiveMTU < L2CAPConnection.MINIMUM_MTU)				|| ((maxPacketSize >= 0) && (receiveMTU > maxPacketSize)))			throw new IllegalArgumentException("receiveMTU"); //$NON-NLS-1$		if ((transmitMTU < L2CAPConnection.MINIMUM_MTU)				|| ((maxPacketSize >= 0) && (transmitMTU > maxPacketSize)))			throw new IllegalArgumentException("transmitMTU"); //$NON-NLS-1$		if (server == null)			throw new IllegalArgumentException("server cannot be null"); //$NON-NLS-1$		this.serverId = server;		this.listener = listener;		this.receiveMTU = receiveMTU;		this.transmitMTU = transmitMTU;	}	/**	 * maximum size of received packet, see	 * {@link L2CAPConnection#getReceiveMTU()} for details.	 */	public final int receiveMTU;	/**	 * maximum size of transmitted packet, see	 * {@link L2CAPConnection#getTransmitMTU()} for details.	 */	public final int transmitMTU;	/**	 * Returns device name.	 * 	 * @return device name, never <code>null</code>.	 */	public static String getDeviceName() {		return deviceName;	}	/**	 * Server's UUID.	 */	public final UUID serverId;	/**	 * Retrieves device name in the form of	 * <code>bluetooth-address:friendly-name</code>.	 * 	 * @param device	 *            the device to query	 * @param alwaysIncludeBTAddress	 *            if <code>true</code> then the bluetooth address is included	 *            even when a friendly name is available.	 * @return device name.	 */	public static String getDeviceName(final RemoteDevice device,			final boolean alwaysIncludeBTAddress) {		final StringBuffer buf = new StringBuffer();		try {			final String friendlyName = device.getFriendlyName(false);			if ((friendlyName != null) && (friendlyName.length() != 0)) {				if (alwaysIncludeBTAddress) {					buf.append(device.getBluetoothAddress());					buf.append(':');				}				buf.append(friendlyName);			} else {				buf.append(device.getBluetoothAddress());			}		} catch (IOException e) {			Logger.warn("Peer.getDeviceName(): cannot get friendly name", e); //$NON-NLS-1$		}		return buf.toString();	}	/**	 * The error listener instance.	 */	protected final IErrorListener listener;	/**	 * Maximum number of clients that the server can handle. This is the maximum	 * ID aswell.	 */	public static final byte MAX_CLIENTS = 10;	/**	 * A cache of integer ids.	 */	private static Byte[] ids = new Byte[MAX_CLIENTS];	static {		for (byte i = 0; i < Peer.MAX_CLIENTS; i++) {			Peer.ids[i] = new Byte(i);		}	}	/**	 * Server always has ID of 0.	 */	public static final byte SERVER_ID = 0;	/**	 * Invokes	 * {@link IErrorListener#errorOccured(byte, int, boolean, Exception)}	 * safely.	 * 	 * @param peerID	 *            error occured during communication with this peer. For server	 *            peer use the {@link Peer#SERVER_ID} id.	 * @param errorHint	 *            where the error occured.	 * @param listener	 *            if not <code>null</code> then the error occured in one of	 *            listener methods.	 * @param ex	 *            the exception.	 */	protected final void invokeErrorOccured(byte peerID, int errorHint,			String listener, final Exception ex) {		try {			if (listener != null)				Logger.error("Peer.listener." + listener + " failed", ex); //$NON-NLS-1$ //$NON-NLS-2$			this.listener.errorOccured(peerID, errorHint, listener != null, ex);		} catch (Exception e) {			Logger					.error(							"Peer.invokeErrorOccured(): listener.errorOccured() failed", //$NON-NLS-1$							e);		}	}	/**	 * Efficiently converts given ID into an Integer instance.	 * 	 * @param id	 *            the id to convert. The id must not be negative. The id must be	 *            less than or equal to {@link #MAX_CLIENTS}.	 * @return Integer instance.	 */	public static Byte getID(final byte id) {		return ids[id];	}	/**	 * Returns maximum number of connections that the peer may open.	 * 	 * @return number of connections or <code>-1</code> if we failed to detect	 *         this number.	 */	public static int getMaxConnections() {		getDevice();		// bluetooth has been initialized, return the number of connections		return maxConnections;	}	/**	 * Returns maximum packet size (the MTU value) that the bluetooth subsystem	 * can handle.	 * 	 * @return MTU or <code>-1</code> if we failed to detect this number.	 */	public static int getMaxPacketSize() {		getDevice();		// bluetooth has been initialized, return the number of connections		return maxPacketSize;	}}

⌨️ 快捷键说明

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