1 19 package org.lucane.common.net; 20 21 import java.io.*; 22 import java.net.*; 23 24 25 28 public class ObjectConnection 29 { 30 private Socket socket; 32 private OutputStream output; 33 private InputStream input; 34 private ObjectListeningThread listener; 35 36 41 public ObjectConnection(Socket socket) 42 { 43 this.listener = new ObjectListeningThread(this); 44 this.socket = socket; 45 try { 46 this.output = socket.getOutputStream(); 47 this.input = socket.getInputStream(); 48 } catch(Exception e) {} 49 } 50 51 56 public void addObjectListener(ObjectListener ol) 57 { 58 this.listener.addObjectListener(ol); 59 } 60 61 64 public void listen() 65 { 66 this.listener.start(); 67 } 68 69 74 public void write(Serializable o) 75 throws IOException 76 { 77 byte[] data = ObjectZipper.objectToBytes(o); 78 byte[] size = intToBytes(data.length); 79 80 this.output.write(size); 81 this.output.write(data); 82 this.output.flush(); 83 } 84 85 90 public boolean readyToRead() 91 { 92 try { 93 return this.socket.getInputStream().available() > 0; 94 } catch(Exception e) {e.printStackTrace();} 95 96 return false; 97 } 98 99 104 public Serializable read() 105 throws IOException, ClassNotFoundException 106 { 107 byte[] size = new byte[4]; 108 this.input.read(size); 109 110 byte[] data = new byte[bytesToInt(size)]; 111 112 int length = 0; 113 while(length < data.length) 114 length += this.input.read(data, length, data.length-length); 115 116 return ObjectZipper.bytesToObject(data); 117 } 118 119 124 public String readString() 125 throws IOException, ClassNotFoundException 126 { 127 return (String )this.read(); 128 } 129 130 133 public void close() 134 { 135 this.listener.close(); 136 137 try { 138 output.close(); 139 input.close(); 140 socket.close(); 141 } catch(Exception e) {} 142 } 143 144 146 149 protected static byte[] intToBytes(int value) 150 { 151 byte[] bytes = new byte[4]; 152 153 for(int i=0; i<bytes.length; i++) 154 { 155 int offset = (bytes.length-i-1) * 8; 156 int mask = 0xff << offset; 157 bytes[i] = (byte)(value >>> offset); 158 } 159 160 return bytes; 161 } 162 163 166 protected static int bytesToInt(byte[] bytes) 167 { 168 int value = 0; 169 170 for(int i=0; i<bytes.length; i++) 171 { 172 value = value << 8; 173 value += bytes[i] & 0xff; 174 } 175 176 return value; 177 } 178 } 179 | Popular Tags |