1 7 package com.maverick.multiplex; 8 9 import java.io.IOException ; 10 import java.net.Socket ; 11 12 import com.maverick.util.ByteArrayReader; 13 import com.maverick.util.ByteArrayWriter; 14 15 21 public class SocketChannel extends Channel { 22 23 String hostname; 24 int port; 25 Socket socket; 26 IOStreamConnector input; 27 IOStreamConnector output; 28 29 public static final String CHANNEL_TYPE = "socket-channel"; 30 31 public SocketChannel(Socket socket, String hostname, int port) { 32 super(CHANNEL_TYPE, 34000, 32768); 33 this.socket = socket; 34 this.hostname = hostname; 35 this.port = port; 36 } 37 38 public SocketChannel() { 39 super("socket-channel", 34000, 32768); 40 this.equals(null); 41 } 42 43 44 47 public byte[] open(byte[] data) throws IOException { 48 ByteArrayReader reader = new ByteArrayReader(data); 49 hostname = reader.readString(); 50 port = (int)reader.readInt(); 51 52 socket = new Socket (hostname, port); 53 54 return null; 55 } 56 57 60 public byte[] create() throws IOException { 61 62 ByteArrayWriter msg = new ByteArrayWriter(); 63 msg.writeString(hostname); 64 msg.writeInt(port); 65 return msg.toByteArray(); 66 } 67 68 public void onChannelOpen(byte[] data) { 69 70 try { 71 input = new IOStreamConnector(socket.getInputStream(), 72 getOutputStream()); 73 output = new IOStreamConnector(getInputStream(), 74 socket.getOutputStream()); 75 } catch(IOException ex) { 76 close(); 77 } 78 } 79 80 public void onChannelClose() { 81 if(input!=null) 82 input.close(); 83 if(output!=null) 84 output.close(); 85 } 86 87 } 88 | Popular Tags |