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

📄 peerconnection.java

📁 jxme的一些相关程序,主要是手机上程序开发以及手机和计算机通信的一些程序资料,程序编译需要Ant支持
💻 JAVA
字号:
/************************************************************************
 *
 * $Id: PeerConnection.java,v 1.2 2002/03/04 21:43:00 echtcherbina Exp $
 *
 * Copyright (c) 2001 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *       Sun Microsystems, Inc. for Project JXTA."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
 *    must not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact Project JXTA at http://www.jxta.org.
 *
 * 5. Products derived from this software may not be called "JXTA",
 *    nor may "JXTA" appear in their name, without prior written
 *    permission of Sun.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL SUN MICROSYSTEMS OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Project JXTA.  For more
 * information on Project JXTA, please see
 * <http://www.jxta.org/>.
 *
 * This license is based on the BSD license adopted by the Apache Foundation.
 *********************************************************************************/

package net.jxta.impl.rendezvous;

import java.net.*;
import java.util.*;

import org.apache.log4j.Category; import org.apache.log4j.Priority;

import net.jxta.id.*;
import net.jxta.peer.*;
import net.jxta.protocol.*;
import net.jxta.document.*;
import net.jxta.rendezvous.*;
import net.jxta.endpoint.*;
import net.jxta.discovery.*;
import net.jxta.peergroup.*;
import net.jxta.impl.util.*;

// We need to import the EndpointReceiveQueue
import net.jxta.impl.endpoint.EndpointReceiveQueue;

/**
 * Class used to manage a connection with a client or a rendezvous peer.
 **/

public class PeerConnection implements Runnable {

    private final static Category LOG = Category.getInstance(PeerConnection.class.getName());
    public  final static int MaxNbOfMessages = 40;
    
    private String  peer = null;
    private String  peerName = null;
    private long    lease = 0;
    private boolean connected = false;
    private EndpointService endpoint = null;
    private DiscoveryService discovery = null;
    private EndpointReceiveQueue queue = null;
    private Thread thread = null;

    /**
     *Constructor for the PeerConnection object
     *
     * WARNING: this constructor can be used for simply testing against
     * existing connection. This constructor must NOT allocate any resources.
     */
    public PeerConnection(PeerGroup group, String p, long l) {

	this.peer = p;
	this.endpoint = group.getEndpointService();
	this.discovery = group.getDiscoveryService();
	this.connected = true;

	if ((System.currentTimeMillis() + l) < 0) {
	    // This is the case when the lease is infinite
	    this.lease = l;
	} else {
	    this.lease = System.currentTimeMillis() + l;
	}

    }

    // Try to connect. This operation is idempotent.
    public synchronized void connect () {

	// We assume that we can be connected.
	connected = true;

	if (queue == null) {
	    // There is new queue. Create one.
	    queue = new EndpointReceiveQueue();
	    queue.setMaxNbOfMessages (MaxNbOfMessages);
	}

	// Start the background thread.
	if (thread != null) {
	    // Nothing to do
	    return;
	}
	thread = new Thread (this, "RDV Connection to " + getPeerName());
	thread.start();
	Thread.currentThread().yield();
    }

    private synchronized void setThreadName () {

	if (thread != null) {
	    try {
		thread.setName ("RDV Connection [queue = " + queue.getNbOfQueuedMessages() + " ] to " + getPeerName());
	    } catch (Exception ez1) {
		if (LOG.isEnabledFor(Priority.ERROR)) LOG.error("Cannot change thread name", ez1);
	    }
	}
    }

    // Get the peer name. If the symobolic name is available, use it,
    // otherwise returns the peer id.
    public synchronized String getPeerName() {

	// If we already have a name used it.
	if (peerName != null) {
	    return peerName;
	}
	// Try to see if we have a peer advertisement for this peer.
	// This is very likely.
	try {
	    Enumeration enum = discovery.getLocalAdvertisements (DiscoveryService.PEER,
								 "PID",
								 peer);
	    if ((enum != null) && (enum.hasMoreElements())) {
		PeerAdvertisement adv = (PeerAdvertisement) enum.nextElement();
		peerName = adv.getName();
	    }
	} catch (Exception ez1) {
	    peerName = null;
	    return peer;
	}
	return peerName;
    }


    // Set the lease.
    public synchronized void setLease (long lease) {
	this.lease = lease;
    }

    // Get the lease
    public synchronized long getLease() {
	return lease;
    }

    // Test if the connection is up
    public synchronized boolean isConnected() {
	return connected;
    }

    // Set the peer id
    public synchronized void setPeer (String peer) {
	this.peer = peer;
    }

    // Get the peer id
    public synchronized String getPeer() {
	return peer;
    }


    // get an EndpointMessenger to the remote peer.
    private EndpointMessenger getMessenger(String pName, String pParam) {

	EndpointMessenger tmpMessenger = null;

        try {
            tmpMessenger = endpoint.getMessenger(mkAddress(peer,
							   pName,
							   pParam));
	    return tmpMessenger;
	} catch (Exception e) {
	    return null;
	}
    }


    // doSendMessage actually sends the message to the remote peer.
    private void doSendMessage (Message msg) {

	if (!isConnected()) {
	    // This connection is closed. Do nothing.
	    return;
	}

	// Recover the service name and parameter from the message.
	EndpointAddress dstAddress = msg.getDestinationAddress();
	String pName = dstAddress.getServiceName();
	String pParam = dstAddress.getServiceParameter();

	EndpointMessenger messenger = getMessenger (pName, pParam);
	if (messenger == null) {
	    // We cannot get a Messenger. Connection is broken.
	    notifyFailure();
	    return;
	}
	 
	try {
	    messenger.sendMessage (msg);
	} catch (Exception e) {
	    // Connection is broken.
	    notifyFailure();
	}
    }


    // Public method that sends messages to the remote peer.
    // Only queue the message and let the background thread actually sends the message.

    public void sendMessage (Message msg, String pName, String pParam) {

	if (!isConnected()) {
	    // No connection. The message is dropped.
	    return;
	}

	// Set the destination of the message, so the background thread can
	// recover pParam and pName.
	EndpointAddress dstAddress = msg.getDestinationAddress();
	if (dstAddress != null) {
	    dstAddress.setServiceName (pName);
	    dstAddress.setServiceParameter (pParam);
	} else {
	    dstAddress = mkAddress (peer, pName, pParam);
	}
	msg.setDestinationAddress (dstAddress);

	// Queue the message.
	synchronized (this) {
	    queue.push (msg);
	    setThreadName();
	}
    }

    /**
     * Build an EndpointAddress the EndpointRouter can use.
     */
    private EndpointAddress mkAddress(String destPeer) {
        try {
            PeerID asID = (PeerID) IDFactory.fromURL(new URL(destPeer));
            String asString = "jxta://"
                + asID.getUniqueValue().toString();
            EndpointAddress addr = endpoint.newEndpointAddress(asString);
            return addr;
        } catch (Exception e) {
            if (LOG.isEnabledFor(Priority.WARN)) LOG.warn("Invalid peerID string " + destPeer);
            return null;
        }
    }

    /**
     * Build an EndpointAddress the EndpointRouter can use.
     */
    private EndpointAddress mkAddress(String destPeer,
				      String serv,
				      String parm) {

        EndpointAddress addr = mkAddress(destPeer);
        addr.setServiceName(serv);
        addr.setServiceParameter(parm);
        return addr;
    }

    public boolean equals(Object obj) {
	if (peer.equals(((PeerConnection) obj).peer)) {
	    return true;
	} else {
	    return false;
	}
    }

    // This is the background Thread. While the connection is active, takes
    // messages from the queue and send it.
    public void run() {
	
	Message msg = null;
	while (true) {

	    if (!isConnected()) {
		// This connection is closed. Exit.
		close();
		return;
	    }
	    try {
		// Wait for messages to be sent.
		msg = queue.waitForMessage();
		setThreadName();
	    } catch (InterruptedException e) {
		if (!isConnected()) {
		    // The connection is just being close. This Thread must exit.
		    close();
		    return;
		} else {
		    // This is a failure.
		    notifyFailure();
		    continue;
		}
	    }
	    // Send the message.
	    doSendMessage (msg);
	}
    }

    // We just close the connection and set the connected status to false.
    private synchronized void notifyFailure() {
	close();
	connected = false;
    }


    // Close the connection. This operation must be idempotent.
    public synchronized void close() {

	connected = false;
	if (queue != null) {
	    queue.close();
	    queue = null;
	}
	if (thread != null) {
	    try {
		thread.interrupt();
		thread = null;
	    } catch (Exception ez1) {
		if (LOG.isEnabledFor(Priority.WARN)) LOG.warn("Cannot interrupt RDV thread for " + getPeerName(), ez1);
	    }
	}
    }

    // Just in case the code that allocated an instance of this object forgot to do "close".
    public void finalize() {
	close();
    }

}





⌨️ 快捷键说明

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