1
10package org.jstk.ssl;
11
12import java.net.*;
13import java.io.*;
14import java.nio.ByteBuffer;
15import java.nio.channels.SocketChannel;
16
17public abstract class JSTKSocket {
18 private static class SocketWrapper extends JSTKSocket {
19 private Socket sock = null;
20 private SocketWrapper(Socket sock){
21 this.sock = sock;
22 }
23 public int read(JSTKBuffer buf) throws IOException {
24 byte[] ba = buf.getByteArray();
25 int n = sock.getInputStream().read(ba, 0, ba.length);
26 buf.setNBytes(n);
27 return n;
28 }
29 public void write(JSTKBuffer buf) throws IOException {
30 byte[] ba = buf.getByteArray();
31 sock.getOutputStream().write(ba, 0, buf.getNBytes());
32 }
33 public Socket getSocket(){
34 return sock;
35 }
36 public void close(){
37 try {
38 sock.close();
39 } catch (Exception e){
40 System.err.println("Exception in Socket.close(). Ignoring ... Exception: " + e);
41 }
42 }
43 }
44
45 private static class SocketChannelWrapper extends JSTKSocket {
46 private SocketChannel sc = null;
47 private SocketChannelWrapper(SocketChannel sc){
48 this.sc = sc;
49 }
50 public int read(JSTKBuffer buf) throws IOException {
51 ByteBuffer bb = buf.getByteBuffer();
52 bb.clear();
53 return sc.read(bb);
54 }
55 public void write(JSTKBuffer buf) throws IOException {
56 ByteBuffer bb = buf.getByteBuffer();
57 bb.flip();
58 sc.write(bb);
59 }
60 public Socket getSocket(){
61 return sc.socket();
62 }
63 public void close(){
64 try {
65 sc.close();
66 } catch (Exception e){
67 System.err.println("Exception in SocketChannel.close(). Ignoring ... Exception: " + e);
68 }
69 }
70 }
71
72 public static JSTKSocket getInstance(Socket sock){
73 return new SocketWrapper(sock);
74 }
75
76 public static JSTKSocket getInstance(SocketChannel sc){
77 return new SocketChannelWrapper(sc);
78 }
79
80 public abstract void close();
81 public abstract int read(JSTKBuffer jbuf) throws IOException;
82 public abstract void write(JSTKBuffer jbuf) throws IOException;
83 public abstract Socket getSocket();
84}
85