1 23 package fr.dyade.aaa.jndi2.msg; 24 25 import java.io.*; 26 import java.net.*; 27 28 public class IOControl { 29 33 public static final String SOCKET_SOTIMEOUT = "fr.dyade.aaa.jndi2.socketTimeOut"; 34 35 44 private static int socketTimeOut = 45 Integer.getInteger(SOCKET_SOTIMEOUT, 0).intValue(); 46 47 private Socket socket; 48 49 private BufferedInputStream bis; 50 51 private NetOutputStream nos; 52 53 public IOControl(Socket socket) throws IOException { 54 this.socket = socket; 55 socket.setTcpNoDelay(true); 56 socket.setSoTimeout(socketTimeOut); 57 socket.setSoLinger(true, 1000); 58 nos = new NetOutputStream(socket); 59 bis = new BufferedInputStream(socket.getInputStream()); 60 } 61 62 public Object readObject() 63 throws IOException, ClassNotFoundException { 64 ObjectInputStream ois = new ObjectInputStream(bis); 65 return ois.readObject(); 66 } 67 68 public int readInt() 69 throws IOException { 70 DataInputStream dis = new DataInputStream(bis); 71 return dis.readInt(); 72 } 73 74 public void writeObject(Object obj) throws IOException { 75 nos.send(obj); 76 } 77 78 public void writeInt(int i) throws IOException { 79 nos.send(i); 80 } 81 82 public void close() { 83 try { 84 socket.getInputStream().close(); 85 } catch (IOException exc) {} 86 try { 87 socket.getOutputStream().close(); 88 } catch (IOException exc) {} 89 try { 90 socket.close(); 91 } catch (IOException exc) {} 92 } 93 94 public final Socket getSocket() { 95 return socket; 96 } 97 98 static class NetOutputStream { 99 private ByteArrayOutputStream baos = null; 100 private ObjectOutputStream oos = null; 101 private OutputStream os = null; 102 103 static private final byte[] streamHeader = { 104 (byte)((ObjectStreamConstants.STREAM_MAGIC >>> 8) & 0xFF), 105 (byte)((ObjectStreamConstants.STREAM_MAGIC >>> 0) & 0xFF), 106 (byte)((ObjectStreamConstants.STREAM_VERSION >>> 8) & 0xFF), 107 (byte)((ObjectStreamConstants.STREAM_VERSION >>> 0) & 0xFF) 108 }; 109 110 NetOutputStream(Socket sock) throws IOException { 111 baos = new ByteArrayOutputStream(1024); 112 oos = new ObjectOutputStream(baos); 113 baos.reset(); 114 os = sock.getOutputStream(); 115 } 116 117 void send(Object msg) throws IOException { 118 try { 119 baos.write(streamHeader, 0, 4); 120 oos.writeObject(msg); 121 oos.flush(); 122 123 baos.writeTo(os); 124 os.flush(); 125 } finally { 126 oos.reset(); 127 baos.reset(); 128 } 129 } 130 131 void send(int i) throws IOException { 132 DataOutputStream daos = new DataOutputStream(os); 133 daos.writeInt(i); 134 daos.flush(); 135 } 136 } 137 } 138 | Popular Tags |