Subversion Repositories HomeAutomation

Rev

Rev 976 | Rev 981 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | SVN | RSS feed

Rev Author Line No. Line
976 runge 1
 
2
function HTTP()
3
{
4
}
5
 
6
HTTP.prototype.mySocket = null;
7
HTTP.prototype.myUserCallback = null;
8
HTTP.prototype.myBuffer = null;
9
 
10
HTTP.prototype.request = function(callback, url)
11
{
12
	this.myUserCallback = callback;
13
 
14
	if (this.mySocket)
15
	{
16
		this.mySocket.stop();
17
	}
18
 
19
	var self = this;
20
 
21
	var urlData = this.parseUrl(url);
22
 
23
	/*log("hostname: " + urlData['hostname'] + "\n");
24
	log("path: " + urlData['path'] + "\n");
25
	log("port: " + urlData['port'] + "\n");*/
26
 
27
	this.myBuffer = "";
28
 
29
	this.mySocket = new Socket(function(event, data) { self.socketCallback(event, data); }, urlData['hostname'], urlData['port'], 0);
30
	this.mySocket.start();
31
 
32
	var request = "GET " + urlData['path'] + " HTTP/1.1\n";
33
	request += "Host: " + urlData['hostname'] + "\n";
34
	request += "Connection: close\n";
35
	request += "\n";
36
 
37
	this.mySocket.send(request);
38
}
39
 
40
HTTP.prototype.parseUrl = function(url)
41
{
42
	var result = new Array();
43
	result['port'] = 80;
44
	result['path'] = "/";
45
 
46
	var firstSlash = url.indexOf('/');
47
 
48
	if (firstSlash == -1)
49
	{
50
		result['hostname'] = url;
51
	}
52
	else
53
	{
54
		result['hostname'] = url.substr(0, firstSlash);
55
		result['path'] = url.substr(firstSlash);
56
	}
57
 
58
	var firstColon = result['hostname'].indexOf(':');
59
 
60
	if (firstColon != -1)
61
	{
62
		result['port'] = result['hostname'].substr(firstColon+1);
63
		result['hostname'] = result['hostname'].substr(0, firstColon);
64
	}
65
 
66
	return result;
67
}
68
 
69
HTTP.prototype.socketCallback = function(event, data)
70
{
71
	switch (event)
72
	{
73
	case "EVENT_DATA":
74
	this.myBuffer += unescape(data);
75
	break;
76
 
77
	case "EVENT_CLOSED":
78
	case "EVENT_DIED":
79
	this.mySocket.stop();
80
	this.processBuffer();
81
	break;
82
 
83
	case "EVENT_INACTIVITY":
84
	break;
85
	}
86
}
87
 
88
HTTP.prototype.processBuffer = function()
89
{
90
	var pos = this.myBuffer.indexOf("\n\n");
91
 
92
	var headerData = this.myBuffer.substr(0, pos);
93
	var contentData = this.myBuffer.substr(pos+2);
94
 
95
	var headerLines = headerData.split("\n");
96
 
97
	var header = new Array();
98
	var result = headerLines[0];
99
 
100
	for (var n = 1; n < headerLines.length; n++)
101
	{
102
		var headerParts = headerLines[n].split(":", 2);
103
		header[headerParts[0]] = headerParts[1].trim(' ');
104
	}
105
 
977 runge 106
	this.myBuffer = "";
107
 
976 runge 108
	this.myUserCallback(result, header, contentData);
109
}