4 import java.net.Socket;
7 public class Connection {
10 LinkedList<Response> resps = new LinkedList<Response>();
12 public Connection(String aspec) throws ConnectException {
14 s = new Socket(aspec, 1500);
15 } catch(java.net.UnknownHostException e) {
16 throw(new ConnectException("Could not resolve host " + aspec, e));
17 } catch(IOException e) {
18 throw(new ConnectException("Could not connect to host " + aspec, e));
20 reader = new Reader(s, resps);
24 static private class Reader extends Thread {
25 Exception error = null;
27 Collection<Response> resps;
29 public Reader(Socket s, Collection<Response> resps) {
38 r = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
39 } catch(IOException e) {
46 String state = "start";
47 StringBuilder ct = new StringBuilder();
50 List<List<String>>lines = new LinkedList<List<String>>();
51 List<String>tokens = new LinkedList<String>();
57 if((i = r.read()) < 0) {
58 throw(new IOException("The server closed the connection"));
60 } catch(IOException e) {
70 if(state == "start") {
73 } else if(Character.isWhitespace(c)) {
81 } else if(state == "nl") {
87 throw(new IOException("Illegal response code " + code + " from the server"));
88 } catch(IOException e) {
95 tokens = new LinkedList<String>();
98 resps.add(new Response(code, lines));
101 lines = new LinkedList<List<String>>();
108 } else if(state == "code") {
109 if((c == '-') || Character.isWhitespace(c)) {
111 code = Integer.parseInt(ct.toString());
118 } else if(state == "token") {
119 if(Character.isWhitespace(c)) {
120 tokens.add(ct.toString());
125 } else if(c == '\\') {
127 } else if(c == '"') {
132 } else if(state == "bs") {
135 } else if(state == "cited") {
142 } else if(state == "cbs") {
146 throw(new Error("invalid state " + state));
154 protected void finalize() {
157 } catch(IOException e) {
162 public static void main(String[] args) throws Exception {
163 Connection c = new Connection("pc18");
165 while(c.resps.size() > 0) {
166 System.out.println(c.resps.remove(0));
168 synchronized(c.resps) {