【Java开源代码栏目提醒】:以下是网学会员为您推荐的Java开源代码-ConnectionIDFactory.java,希望本篇文章对您学习有所帮助。
package multiplexer;
import java.io.*;
import java.net.*;
/**
* Instances of this class create instances of the
* <code>ConnectionID</code> class. The information used to
* create a <code>ConnectionID</code> object depends on the
* actual connection the <code>ConnectionID</code> is used
* with. A <code>ConnectionIDFactory</code> object
* encapsulates that information. It facilitates managing
* multiple actual connections.
*/
class ConnectionIDFactory {
// Array of information common to all ConnectionID objects
// associated with the same actual connection
private byte[] commonInfo;
private static final int PORT_NUMBER_LENGTH = 2;
static final int SERIAL_NUMBER_LENGTH = 4;
private int counter = 0;
private int byteSize = -1;
/**
* constructor.
* @param socket The socket that encapsulates the actual
* connection this object will produce
* ConnectionID objects for.
*/
ConnectionIDFactory(Socket socket) {
InetAddress inetAddress = socket.getLocalAddress();
byte[] address = inetAddress.getAddress();
// We include port number to allow for the possibility
// of one <code>Multiplexer</code> object working with
// multiple actual connections from the same host.
int port = socket.getLocalPort();
// Assume only 2 significant bytes in a port number and
// four bytes four bytes for a serial number
commonInfo
= new byte[address.length + PORT_NUMBER_LENGTH];
System.arraycopy(address, 0, commonInfo, 0,
address.length);
int portOffset = address.length;
commonInfo[portOffset] = (byte)port;
commonInfo[portOffset+1] = (byte)(port>>8);
} // constructor(Socket)
/**
* Return the number of bytes that will be used to read or
* write a ConnectionID created by this object.
*/
int getByteSize() {
if (byteSize == -1) {
return commonInfo.length+SERIAL_NUMBER_LENGTH;
} // if
return byteSize;
} // getByteSize()
/**
* Set the number of bytes that will be used to read or
* write a ConnectionID created by this object.
*/
void setByteSize(int newValue) {
byteSize = newValue;
} // setByteSize(int)
/**
* Create a new ConnectionID object.
*/
ConnectionID createConnectionID() {
synchronized (this) {
counter++;
} // synchronized
return new ConnectionID(commonInfo, counter);
} // createConnectionID()
} // class ConnectionIDFactory