1 24 25 package org.objectweb.tribe.channel.tcp; 26 27 import java.io.IOException ; 28 import java.net.InetSocketAddress ; 29 import java.net.ServerSocket ; 30 31 import org.objectweb.tribe.channel.AbstractReliableFifoChannel; 32 import org.objectweb.tribe.channel.AbstractServerChannel; 33 import org.objectweb.tribe.common.Address; 34 import org.objectweb.tribe.common.IpAddress; 35 import org.objectweb.tribe.exceptions.ChannelException; 36 import org.objectweb.tribe.exceptions.NotConnectedException; 37 38 44 public class TcpServerChannel extends AbstractServerChannel 45 { 46 47 private ServerSocket socket; 49 54 public TcpServerChannel() throws IOException 55 { 56 socket = new ServerSocket (); 57 } 58 59 68 public TcpServerChannel(int port) throws IOException 69 { 70 socket = new ServerSocket (port); 71 } 72 73 76 public void bind(Address source) throws ChannelException 77 { 78 if (!(source instanceof IpAddress)) 79 throw new ChannelException("TCP Channels require IP addresses."); 80 IpAddress ip = (IpAddress) source; 81 try 82 { 83 socket.bind(new InetSocketAddress (ip.getAddress(), ip.getPort())); 84 } 85 catch (IOException e) 86 { 87 throw new ChannelException("Error while binding serverSocket on " 88 + source, e); 89 } 90 } 91 92 95 public Address getBindAddress() throws NotConnectedException 96 { 97 if (socket == null) 98 throw new NotConnectedException(); 99 return new IpAddress(socket.getInetAddress(), socket.getLocalPort()); 100 } 101 102 105 public AbstractReliableFifoChannel accept() throws ChannelException 106 { 107 try 108 { 109 return new TcpChannel(socket.accept()); 110 } 111 catch (Exception e) 112 { 113 throw new ChannelException("Error while accepting new connection", e); 114 } 115 } 116 117 120 public void close() throws ChannelException 121 { 122 try 123 { 124 socket.close(); 125 } 126 catch (IOException e) 127 { 128 throw new ChannelException("Error while closing the serverSocket", e); 129 } 130 finally 131 { 132 socket = null; 133 } 134 } 135 136 } | Popular Tags |