File: EventStreamReader.java

package info (click to toggle)
scorched3d 41.3dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 159,620 kB
  • ctags: 26,898
  • sloc: cpp: 110,179; xml: 36,743; ansic: 31,536; makefile: 4,321; sh: 3,708; perl: 1,522; java: 209; python: 188; sql: 146
file content (78 lines) | stat: -rw-r--r-- 1,673 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.net.*;
import java.io.IOException;

public class EventStreamReader extends Thread {

	public interface EventStreamReaderI {
		public void handleData(String s);
	}
	
	static final String CRLF = "\015\012";
	Socket socket_;
	EventStreamReaderI handler;
	String host;
	String url;
	int port;
	
	public EventStreamReader(EventStreamReaderI handler, String host, int port, String url) {
		this.handler = handler;
		this.host = host;
		this.port = port;
		this.url = url;
	}
	
	public void run() {

		InetSocketAddress address = new InetSocketAddress(host, port);
		try {
			socket_ = new Socket();
			socket_.connect(address, 10000); // 10 second timeout
		} catch (IOException ex) {
			if (handler != null) handler.handleData(ex.getMessage());
		}
		
		if (socket_.isConnected()) {
		
			try {
				String connectionString = 
					"GET " + url + " HTTP/1.0" + CRLF +
					"Connection: Close" + CRLF +
					CRLF +
					CRLF;
				socket_.getOutputStream().write(
					connectionString.getBytes());
			} catch (IOException ex) {
				if (handler != null) handler.handleData(ex.getMessage());
			}
		
			byte buffer[] = new byte[256];
			while (socket_.isConnected()) {
		
				try {
					Thread.sleep(10);
				} catch (Exception ex) {
				}
			
				try {
					int amount = socket_.getInputStream().read(buffer);
					if (amount > 0) {
						String s = new String(buffer, 0, amount);
						if (handler != null) handler.handleData(s);
					}
				} catch (IOException ex) {
					if (handler != null) handler.handleData(ex.getMessage());
					break;
				}
			}
		}
		
		close();
	}
	
	public void close() {
		try {
			socket_.close();
		} catch (IOException ioEx) {
		}
	}
}