continuous http stream - vb.net

My app currently sends GET httpwberequests and parses the content after reading the response stream for each request and the repeats this process over and over. I need to implement a continuous http stream which uses the same GET request but the connection stays open, from what I understand. how would I change my existing code to do this?
Dim responseReader As StreamReader = Nothing
Dim Reader As StreamReader = Nothing
Dim responseData As String = ""
Dim webresponse As HttpWebResponse = Nothing
Dim responseStream As Stream = Nothing
Dim returnContent As String = Nothing
Dim cdata As Integer = 0
webRequest = TryCast(System.Net.WebRequest.Create(url), HttpWebRequest)
Try
webresponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
responseStream = webresponse.GetResponseStream
If webresponse.ContentEncoding.ToLower().Contains("gzip") Then
responseStream = New GZipStream(responseStream, CompressionMode.Decompress)
ElseIf webresponse.ContentEncoding.ToLower().Contains("deflate") Then
responseStream = New DeflateStream(responseStream, CompressionMode.Decompress)
End If
Reader = New StreamReader(responseStream, Encoding.Default)
responseData = Reader.ReadToEnd()
Catch
Throw
Finally
webRequest.GetResponse().GetResponseStream().Close()
Reader.close()
End Try
Return responseData
The streaming HTTP implementation allows one to cosume data in real time over a single persistent HTTp request. It access a data feed that continues to send activities on that response. I need to read data from the response, process it and then continue reading from the response and continue this process until the connection is closed.
Would this be like a asynchronous request instead?

This is actually one of the goals of HTML5. You can take a look at http://socket.io/ to see implementations that work for HTML4 browsers

Related

Problem with "try-catch" in a web request vb.net

I'm making a web request that completes successfully most of the time (target$ is a URL). But occasionally my code throws a valid exception, 404 not found, if the URL target$ doesn't exist, and execution stops. The code:
Sub scrape(target$)
Dim request As WebRequest = WebRequest.Create(target$)
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
txtResponse.Text = ""
txtResponse.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
end sub
The exception, if thrown, happens in the second line, "Dim response...". So I tried adding a "try-catch" as shown.
Sub scrape(target$)
Dim request As WebRequest = WebRequest.Create(target$)
Dim response As WebResponse = request.GetResponse()
Try
Dim dataStream As Stream = response.GetResponseStream()
Catch
exflag = True
End Try
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
txtResponse.Text = ""
txtResponse.Text = responseFromServer
' Clean up the streams and the response.
reader.Close()
response.Close()
end sub
But now when I try to compile the code, VisualStudio tells me that "datastream is not declared" and the compile fails.
What am I doing wrong and how do I catch the exception when it's thrown?
Thanks...

Why would my VB.NET WebRequest suddenly stop working?

A while ago I wrote a programme in VB.NET to use the Betfair Exchange API. It has worked perfectly for months, but overnight on Tuesday it stopped working. I can still log in, but from Wednesday I have been unable to get anything else from the server.
Betfair are investigating, but according to them nobody else seems to be experiencing the same problem - although I'm not sure how many will be using VB.NET.
Below is the function I have been using to obtain data from the API. Like I said it was working on Tuesday night but not from Wednesday morning. Is there anything here which is "not perfect" or "could be better", or perhaps there is some alternative code I could try? Or is there something which might have happened on my pc which has caused the problem?
The programme falls over at the line "dataStream = request.GetRequestStream() ". The error is "Received an unexpected EOF or 0 bytes from the transport stream."
I would be grateful for any advice that anyone could offer. Thank you!
Public Function CreateRequest(ByVal postData As String, Optional ByVal accountsApi As Boolean = False)
Dim Url As String = "https://api.betfair.com/exchange/betting/json-rpc/v1"
If accountsApi Then Url = "https://api.betfair.com/exchange/account/json-rpc/v1"
Dim request As WebRequest = Nothing
Dim dataStream As Stream = Nothing
Dim response As WebResponse = Nothing
Dim strResponseStatus As String = ""
Dim reader As StreamReader = Nothing
Dim responseFromServer As String = ""
Try
request = WebRequest.Create(New Uri(Url))
request.Method = "POST"
request.ContentType = "application/json-rpc"
request.Headers.Add(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8")
request.Headers.Add("X-Application", appKey)
request.Headers.Add("X-Authentication", sessToken)
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) ' Data to post such as ListEvents, ListMarketCatalogue etc
request.ContentLength = byteArray.Length ' Set the ContentLength property of the WebRequest.
dataStream = request.GetRequestStream() ' Get the request stream.
dataStream.Write(byteArray, 0, byteArray.Length) ' Write the data to the request stream.
dataStream.Close() ' Close the Stream object.
response = request.GetResponse() ' Get the response.
strResponseStatus = CType(response, HttpWebResponse).StatusDescription ' Display the status below if required
dataStream = response.GetResponseStream() ' Get the stream containing content returned by the server.
reader = New StreamReader(dataStream) ' Open the stream using a StreamReader for easy access.
responseFromServer = reader.ReadToEnd() ' Read the content.
reader.Close() : dataStream.Close() : response.Close()
Catch ex As Exception
MsgBox("CreateRequest Error" & vbCrLf & ex.Message, MsgBoxStyle.Critical, " Error")
End Try
Return responseFromServer
End Function
I would check that the provider hasn't recently deprecated use of TLS 1.0 (as they should have done before now, in fact).
If so, your code needs to enforce use of TLS 1.1+:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
This only has to be set once, usually in the (static) type initializer or similar.
And I 100% agree with Andrew Mortimer that you should use Using blocks wherever possible. I'd also suggest moving all of your string values into variables or constants to clean things up and keep them maintainable. Eg:
Const ContentType As String = "application/json-rpc"
...
request.ContentType = ContentType
UPDATE
I just found this announcement on their site:
https://forum.developer.betfair.com/forum/developer-program/announcements/33563-tls-1-0-no-longer-supported-from-1st-december-all-betfair-api-endpoints
If you are allowed to use external dependencies within this project I would recommend using RestSharp nuget package it works really well for creating API requests and getting there response without having to use httpclient which gets messy.
Link: https://restsharp.dev/

Visual Basic convert string to audio (WAV) file and play

I'm using a VB win form and need to play a wav from string but I don't know how to do it.
Dim URl As String ="http://localhost/main.php?command=readdata"
Dim request As HttpWebRequest = HttpWebRequest.Create(URl)
request.Proxy = Nothing
request.UserAgent = "Test"
Dim response As HttpWebResponse = request.GetResponse
Dim responseStream As System.IO.Stream = response.GetResponseStream
Dim Reader As New System.IO.StreamReader(responseStream)
Dim data As String = Reader.ReadToEnd
Reader.Close()
Dim AudioData As String = Hex2String(data)
'here i wont play and save this data
You don't want to read the data as a string, since it's not a string. WAV data is binary data. It's meaningless as a string, and if you encode it as a string, you may lose some data in the process. So, if you aren't converting it to a string, you don't need the StreamReader at all. Just create a new file as a stream, and then copy all the bytes from the one stream to the other:
Dim url As String ="http://localhost/main.php?command=readdata"
Dim request As HttpWebRequest = HttpWebRequest.Create(url)
request.Proxy = Nothing
request.UserAgent = "Test"
Dim response As HttpWebResponse = request.GetResponse()
Using responseStream As Stream = response.GetResponseStream()
Using fileStream As New New FileStream("MyFile.wav", FileMode.CreateNew)
responseStream.CopyTo(fileStream)
End Using
End Using

how to use API in Vb net

What is the best way to issue a http get in VB.net? I want to get the result of a request like
http://89.36.220.56/api.php?photo=urlphoto&point=numberlikes&socks=proxy
Photo = URL Photo
Point = Number
Socks = Proxy
Dim url = "http://89.36.220.56/api.php?photo=urlphoto&point=numberlikes&socks=proxy"
Dim request = DirectCast(WebRequest.Create(url), HttpWebRequest)
Dim response = request.GetResponse()
Dim receiveStream As Stream = response.GetResponseStream()
Dim readStream As New StreamReader(receiveStream, Encoding.UTF8)
Dim data = readStream.ReadToEnd()
response.Close()
readStream.Close()

FTP UPLOAD to AS/400 from VB.NET

I am attempting to perform a FTP Put function to an AS/400 IBM Mainframe with VB.NET. I am able to upload a file however, I need to be able to capture each output response from the mainframe for logging purposes. In short capture what prints out on the cmd screen if I were to perform the FTP manually. Any suggestions would be greatly appreciated.
Depending on the library you are using, you should be able to get some kind of response object or string from the FTP server for each command you submit. You can then parse these responses and dump them into a file/destination/source of your choosing.
EDIT: Since you're using the FTPWebRequest/Response library, you'll want to have your FTPWebRequest object dump its results into the FTPWebResponse object and then read the entire stream with code something like this:
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(serverUri), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectory
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Dim responseStream As Stream = Nothing
Dim readStream As StreamReader = Nothing
Try
responseStream = response.GetResponseStream()
readStream = New StreamReader(responseStream, System.Text.Encoding.UTF8)
If readStream IsNot Nothing Then
Console.WriteLine(readStream.ReadToEnd())
End If
Console.WriteLine("List status: " & response.StatusDescription)
Finally
If readStream IsNot Nothing Then
readStream.Close()
End If
If response IsNot Nothing Then
response.Close()
End If
End Try
Return True
End Function
You should be able to tailor this code to your own in order to retrieve the response details you need.