001package arcommon.net; 002 003import arcommon.MyThread; 004import arcommon.StringUtil; 005 006public abstract class LineConnectionThread extends MyThread { 007 008 private LineConnection lineConnection; 009 010 public LineConnectionThread() { 011 ; 012 } 013 014 public LineConnectionThread(LineConnection plineConnection) { 015 lineConnection = plineConnection; 016 } 017 018 public LineConnectionThread(String name) { 019 super(name); 020 } 021 022 public LineConnectionThread(String name, LineConnection plineConnection) { 023 super(name); 024 lineConnection = plineConnection; 025 } 026 027 protected void doLoop() { 028 try { 029 String line = readLine(); 030 onReadLine(line); 031 } catch (LineConnectionDisconnectException e) { 032 onDisconnect(); 033 requestToStop(); 034 return ; 035 } 036 } 037 038 public boolean isConnected() { 039 if (lineConnection == null) { 040 return false; 041 } 042 return lineConnection.isConnected(); 043 } 044 045 public void sendLine(String text) { 046 if (lineConnection == null || !lineConnection.isConnected()) { 047 return ; 048 } 049 050 lineConnection.sendLine(text); 051 } 052 053 public void sendNumber(int number) { 054 sendLine("" + number); 055 } 056 057 public String readLine() throws LineConnectionDisconnectException { 058 if (!isConnected()) { 059 throw new LineConnectionDisconnectException(); 060 } 061 062 String line = lineConnection.readLine(); 063 if (!isConnected()) { 064 throw new LineConnectionDisconnectException(); 065 } 066 067 return line; 068 } 069 070 public int readNumber() throws LineConnectionDisconnectException { 071 String string = readLine(); 072 return StringUtil.stringToInt(string); 073 } 074 075 public void close() { 076 if (lineConnection == null) { 077 return ; 078 } 079 080 lineConnection.close(); 081 lineConnection = null; 082 } 083 084 public void setLineConnection(LineConnection plineConnection) { 085 lineConnection = plineConnection; 086 } 087 088 public LineConnection getLineConnection() { 089 return lineConnection; 090 } 091 092 protected abstract void onReadLine(String line) throws LineConnectionDisconnectException; 093 protected abstract void onDisconnect(); 094}