001package arcommon.net; 002 003import java.io.IOException; 004import java.net.BindException; 005import java.net.ServerSocket; 006import java.net.Socket; 007import java.net.SocketException; 008 009public class LineServer { 010 private ServerSocket serverSocket; 011 private boolean isListening; 012 013 public LineServer(int port) { 014 try { 015 serverSocket = new ServerSocket(port); 016 isListening = true; 017 } catch (BindException e) { 018 isListening = false; 019 if (e.getMessage().equals("Address already in use (Bind failed)")) { 020 return ; 021 } 022 throw new RuntimeException(e); 023 } catch (IOException e) { 024 isListening = false; 025 throw new RuntimeException(e); 026 } 027 } 028 029 public boolean isListening() { 030 return isListening; 031 } 032 033 public LineConnection getConnection() { 034 Socket clientSocket = null; 035 try { 036 clientSocket = serverSocket.accept(); 037 LineConnection lineConnection = new LineConnection(clientSocket); 038 return lineConnection; 039 } catch (SocketException e) { 040 if (e.getMessage().equals("socket closed") || e.getMessage().equals("Socket closed")) { 041 isListening = false; 042 return null; 043 } 044 throw new RuntimeException(e); 045 } catch (IOException e) { 046 throw new RuntimeException(e); 047 } 048 } 049 050 public void close() { 051 try { 052 isListening = false; 053 serverSocket.close(); 054 } catch (IOException e) { 055 throw new RuntimeException(e); 056 } 057 } 058}