1.
import java.net.InetAddress;
import java.net.UnknownHostException;
public class NetWork {
//static fields and static block
//InetAddress of the local host
private static InetAddress local = null;
//integer version of the local host
private static int packedLocal = 0;
static {
try{
local = InetAddress.getLocalHost();
}catch(UnknownHostException e){
e.printStackTrace();
}
System.out.println("localhost : " + local);
packedLocal = translate(local);
}
public static InetAddress getLocalHost(){
return local;
}
public static String getLocalHostName(){
return local.getHostName();
}
public static String getLocalMachineName(){
String hostname = local.getHostName();
int machEndIndex = hostname.indexOf('.');
if(machEndIndex == -1)
return hostname;
else
return hostname.substring(0, machEndIndex);
}
public static boolean isLocal(InetAddress address){
return local.equals(address);
}
public static boolean isLocal(int packedAddress){
return packedAddress == packedLocal;
}
/**
* return an integer representation of the specified
* InetAddress. This is used for efficiency
*/
public static int translate(InetAddress address){
byte[] ad = address.getAddress();//原始IP地址
if(ad.length != 4)
throw new IllegalArgumentException("only accept 32-byte IP address");
int packedAddress = ((ad[0] << 24) & 0xFF000000) |
((ad[1] << 16) & 0xFF0000) |
((ad[2] << 8) & 0xFF00) |
(ad[3] & 0xFF);
return packedAddress;
}
/**
* return an InetAddress representation of the specified integer.
* This is used for performance improvements in serivalization.
*/
public static InetAddress translate (int packed)
throws UnknownHostException{
int[] ad = new int[4];
ad[0] = (packed >>> 24);
ad[1] = ((packed >>> 16) & 0x000000FF);
ad[2] = ((packed >>> 8) & 0x000000FF);
ad[3] = (packed & 0x000000FF);
StringBuffer buf = new StringBuffer();
buf.append(ad[0]);
buf.append(".");
buf.append(ad[1]);
buf.append(".");
buf.append(ad[2]);
buf.append(".");
buf.append(ad[3]);
return InetAddress.getByName(buf.toString());
}
public static String translateToString(int packed){
int[] ad = new int[4];
ad[0] = (packed >>> 24);
ad[1] = ((packed >>> 16) & 0x000000FF);
ad[2] = ((packed >>> 8) & 0x000000FF);
ad[3] = (packed & 0x000000FF);
StringBuffer buf = new StringBuffer();
buf.append(ad[0]);
buf.append(".");
buf.append(ad[1]);
buf.append(".");
buf.append(ad[2]);
buf.append(".");
buf.append(ad[3]);
return buf.toString();
}
public static void main(String[] args){
InetAddress localhost = getLocalHost();
System.out.println("Local Host Name is : " + getLocalHostName());
System.out.println("Local Host Machine Name is : " + getLocalMachineName());
if(isLocal(localhost))
System.out.println(localhost.getHostName() + " is Local Host.");
int intforaddress = translate(localhost);
System.out.println("localhost integer representation is " + intforaddress);
System.out.println("localhost string representation is " + translateToString(intforaddress));
System.out.println(translateToString(intforaddress).toString());
}
}
2. public interfece Externalizable extendx Serializable
Externalizable 實(shí)例類的惟一特性是可以被寫入序列化流中,該類負(fù)責(zé)保存和恢復(fù)實(shí)例內(nèi)容。 若某個(gè)要完全控制某一對(duì)象及其超類型的流格式和內(nèi)容,則它要實(shí)現(xiàn) Externalizable 接口的 writeExternal 和 readExternal 方法。這些方法必須顯式與超類型進(jìn)行協(xié)調(diào)以保存其狀態(tài)。這些方法將代替自定義的 writeObject 和 readObject 方法實(shí)現(xiàn)。
Serialization 對(duì)象將使用 Serializable 和 Externalizable 接口。對(duì)象持久性機(jī)制也可以使用它們。要存儲(chǔ)的每個(gè)對(duì)象都需要檢測(cè)是否支持 Externalizable 接口。如果對(duì)象支持 Externalizable,則調(diào)用 writeExternal 方法。如果對(duì)象不支持 Externalizable 但實(shí)現(xiàn)了 Serializable,則使用 ObjectOutputStream 保存該對(duì)象。
在重構(gòu) Externalizable 對(duì)象時(shí),先使用無(wú)參數(shù)的公共構(gòu)造方法創(chuàng)建一個(gè)實(shí)例,然后調(diào)用 readExternal 方法。通過(guò)從 ObjectInputStream 中讀取 Serializable 對(duì)象可以恢復(fù)這些對(duì)象。
Externalizable 實(shí)例可以通過(guò) Serializable 接口中記錄的 writeReplace 和 readResolve 方法來(lái)指派一個(gè)替代對(duì)象。
writeExternal
void writeExternal(ObjectOutput out)
throws IOException
- 該對(duì)象可實(shí)現(xiàn) writeExternal 方法來(lái)保存其內(nèi)容,它可以通過(guò)調(diào)用 DataOutput 的方法來(lái)保存其基本值,或調(diào)用 ObjectOutput 的 writeObject 方法來(lái)保存對(duì)象、字符串和數(shù)組。
-
-
- 參數(shù):
out
- 要寫入對(duì)象的流
- 拋出:
IOException
- 包含可能發(fā)生的所有 I/O 異常
readExternal
void readExternal(ObjectInput in)
throws IOException,
ClassNotFoundException
- 對(duì)象實(shí)現(xiàn) readExternal 方法來(lái)恢復(fù)其內(nèi)容,它通過(guò)調(diào)用 DataInput 的方法來(lái)恢復(fù)其基礎(chǔ)類型,調(diào)用 readObject 來(lái)恢復(fù)對(duì)象、字符串和數(shù)組。readExternal 方法必須按照與 writeExternal 方法寫入值時(shí)使用的相同順序和類型來(lái)讀取這些值。
-
-
- 參數(shù):
in
- 為了恢復(fù)對(duì)象而從中讀取數(shù)據(jù)的流
- 拋出:
IOException
- 如果發(fā)生 I/O 錯(cuò)誤
ClassNotFoundException
- 如果無(wú)法找到需要恢復(fù)的某個(gè)對(duì)象的類。
import java.io.Externalizable;
import java.net.InetAddress;
public interface EndPoint extends Externalizable {
/**
*
* @return Returns the IP address contained in this endpoint.
*/
public InetAddress getAddress();
/**
* returns the IP address contained in this endpoint.
* enclosed in an integer value.
*/
public int getIntAddress();
/**
* Returns the port number contained in this endpoint.
*/
public int getPort();
/**
* Return true if this endpoint is the local endpoint.
*/
public boolean isLocal();
/**
* Returns true if this endpoint is a multicast endpoint.
*/
public boolean isMulticastEndPoint();
}
import internet.network.NetWork;
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class EndPointImpl implements EndPoint, Comparable, Externalizable{
//Constants
/* Size of this object (in bytes) when marshalled. */
public static final int SIZE = 6;
//Fields
protected InetAddress address;
private int packedAddress;
private int port;
protected boolean local;
//Constructors
/**
* Default constructor for externalization
*/
public EndPointImpl(){
}
public EndPointImpl(InetAddress address, int port){
this.address = address;
this.port = port;
packedAddress = NetWork.translate(address);
local = NetWork.isLocal(packedAddress);
}
public EndPointImpl(int packedAddress, int port){
this.packedAddress = packedAddress;
this.port = port;
this.local = NetWork.isLocal(packedAddress);
//The InetAddress version of the address is computed
//only when needed, to avoid uselesss DNS lookups.
address = null;
}
public InetAddress getAddress() {
if(address == null)
try{
address = NetWork.translate(packedAddress);
}catch(UnknownHostException e){
System.out.println(e.getMessage());
}
return address;
}
public int getIntAddress() {
return this.packedAddress;
}
public int getPort() {
return this.port;
}
public boolean isLocal() {
return this.local;
}
public boolean isMulticastEndPoint() {
return address.isMulticastAddress();
}
////////////////////////////////////////////////////////////
// Methods from Externalizable
////////////////////////////////////////////////////////////
/**
* Restores the content of this object form the marshaled data contained
* in the specified input stream.
*
* @param in the stream to be read.
*/
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
packedAddress = in.readInt();
port = (int) in.readUnsignedShort();
local = NetWork.isLocal(packedAddress);
address = null;
}
/**
* Marshals the content of this object to the specified output stream.
*
* @param out the stream to be written
*/
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(packedAddress);
out.writeShort(port);
}
////////////////////////////////////////////////////////////
// Methods from Object and Comparable
////////////////////////////////////////////////////////////
/**
* Compares this object with the specified object for order.
*/
public int compareTo(Object obj) {
if(this == obj){
return 0;
}
else{
EndPointImpl endpoint = (EndPointImpl) obj;
if(packedAddress < endpoint.packedAddress){
return -1;
}
else if(packedAddress == endpoint.packedAddress){
if(port < endpoint.port)
return -1;
else if(port == endpoint.port)
return 0;
else
return 1;
}
else{
return 1;
}
}
}
public int hashcode(){
return packedAddress ^ port;
}
/**
* Compares two EndPointImpl objects for content equality.
*/
public boolean equals (Object obj){
if(!(obj instanceof EndPointImpl))
return false;
EndPointImpl endpoint = (EndPointImpl) obj;
return (endpoint.packedAddress == packedAddress && endpoint.port == port);
}
/**
* Returns a string representation of this object.
*/
public String toString(){
StringBuffer buf = new StringBuffer();
buf.append("[");
buf.append(NetWork.translateToString(packedAddress));
buf.append(":");
buf.append(port);
buf.append("]");
return buf.toString();
}
public static void main(String[] args) throws FileNotFoundException, IOException{
InetAddress localhost = NetWork.getLocalHost();
EndPointImpl endpoint = new EndPointImpl(localhost, 100);
System.out.println("This EndPoint is : " + endpoint.toString());
EndPointImpl endpoint2 = new EndPointImpl();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("endpoint.txt"));
try {
endpoint.writeExternal(oos);
} catch (IOException e) {
e.printStackTrace();
}
oos.close();
ObjectInputStream ios = new ObjectInputStream(new FileInputStream("endpoint.txt"));
try {
endpoint2.readExternal(ios);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ios.close();
System.out.println("This EndPoint is : " + endpoint2.toString());
}
}