mIRC Home    About    Download    Register    News    Help

Print Thread
Joined: Mar 2014
Posts: 11
T
Pikka bird
OP Offline
Pikka bird
T
Joined: Mar 2014
Posts: 11
So, i'm just learning about sockets, so this is on a very basic level. I'm trying to connect to https://api.twitch.tv/kraken/streams/STREAMNAME/ to get some useful information about the stream. The server uses https, I do have openSSL installed.
Here's my code:
Code:
on *:text:!test:#: {
  if ($sock(twitch)) .sockclose twitch 
  sockopen -e twitch  api.twitch.tv 443 
}
on *:SOCKOPEN:twitch: {
  sockwrite -nt $sockname GET /kraken/streams/tehpolecat HTTP/1.1
  sockwrite -nt $sockname Host: api.twitch.tv
  sockwrite $sockname $crlf
}
on *:SOCKREAD:twitch: {
  if (!$sockerr) { var %sockreader
    sockread %sockreader
    if (self isin %sockreader) { msg #tehpolecat 1 $+ }
    else { msg #tehpolecat 2 $+ }
  sockclose twitch }
  else { msg #tehpolecat Socket Error $+ }
}

In this case it should return "1" but it will always return "2"

I tried echoing the %sockreader variable but the only line i get is
Quote:
HTTP/1.1 200 OK


What am I doing wrong? Probably something obvious. Thanks in advance.

Last edited by Tehpolecat; 09/06/14 10:40 PM.
Joined: Jan 2004
Posts: 1,358
L
Hoopy frood
Offline
Hoopy frood
L
Joined: Jan 2004
Posts: 1,358
A single /sockread does not read the entire server response into the variable. Usually you read line by line, and in addition to the content of the request there are also headers. You're messaging '2' because the first line of the response does -not- contain 'self', and then you close the socket before reading the rest of the lines. To read the whole thing you should use a while loop like while ($sockbr). Also note the request header changes, HTTP/1.1 to HTTP/1.0 to disable chunked transfer encoding (which can screw you up if you aren't writing code to support it) and the addition of the connection header so that twitch will close the connection automatically when the transfer is complete.

Code:
on *:text:!test:#: {
  if ($sock(twitch)) .sockclose twitch 
  sockopen -e twitch api.twitch.tv 443 
}
on *:SOCKOPEN:twitch: {
  sockwrite -nt $sockname GET /kraken/streams/tehpolecat HTTP/1.0
  sockwrite -nt $sockname Host: api.twitch.tv
  sockwrite -nt $sockname Connection: close
  sockwrite $sockname $crlf
}
on *:SOCKREAD:twitch: {
  if ($sockerr) return

  var %sockreader
  sockread %sockreader
  while ($sockbr) {
    if (%sockreader) echo -ag %sockreader
    sockread %sockreader
  }
}


Use [code] to wrap code instead of [quote]

Last edited by Loki12583; 09/06/14 10:29 PM.
Joined: Mar 2014
Posts: 11
T
Pikka bird
OP Offline
Pikka bird
T
Joined: Mar 2014
Posts: 11
Alright, thanks, I'll give it a try

edit: Yeah that works great, thanks

Last edited by Tehpolecat; 09/06/14 11:38 PM.

Link Copied to Clipboard