I am sending and recieving messages from a unix server, all is fine and working as intended...except when I dont get a response from the server, I can confirm the server did get my message, but for whatever reason on their end they dont respond.
I am using the below code on my read, it gets to numberOfBytesRead = and hangs up my app.
If serverStream.CanRead Then
Dim myReadBuffer As Byte() = New Byte(1024) {}
Dim myCompleteMessage As StringBuilder = New StringBuilder()
Dim numberOfBytesRead As Integer = 0
Do
numberOfBytesRead = serverStream.Read(myReadBuffer, 0, myReadBuffer.Length)
If My.Settings.initCompassLive Then
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
Else
myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 2, numberOfBytesRead))
End If
Loop While serverStream.DataAvailable
' MsgBox("You received the following message : " + myCompleteMessage.ToString)
returndata = myCompleteMessage.ToString
Else
MsgBox("Aauth Request Failed: " & returndata)
Exit Sub
End If
I just needed a serverStream.ReadTimeOut = bla bla bla
TYVM
MW
Related
I have a server used to get info from SAPGUI. Everything works fine for a first request but nothing after that. The first iteration waits for a socket event. Once the socket is read for the first time it just loops without reading the receive buffer. I am assuming I need to reset the listener but am having trouble doing so.
'first iteration it works as expected but readbyte is always 0 after that even though it loops through fine.
'what I don't get is that the first iteration it waits for data to come down the socket, but after that it just loops
'and doesn't retreive anything.
Dim listenerSocket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim ipend As IPEndPoint = New IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888)
listenerSocket.Bind(ipend)
listenerSocket.Listen(0)
Dim clientSocket As Socket = listenerSocket.Accept()
Dim Buffer As Byte() = New Byte(clientSocket.SendBufferSize - 1) {}
Dim readByte, sendByte As Integer
Dim Sbuffer As Byte() = System.Text.Encoding.ASCII.GetBytes("Some form of SAP response!")
Dim clientError As System.Net.Sockets.SocketError
Console.WriteLine("Waiting for connection : ")
For infinitecounter = 1 To 3
infinitecounter = 1
readByte = clientSocket.Receive(Buffer)
While (True)
If readByte > 0 Then
Dim rData As Byte() = New Byte(readByte - 1) {}
Array.Copy(Buffer, rData, readByte)
SAPrq = System.Text.Encoding.UTF8.GetString(rData)
SAPpar = Left(SAPrq, 1)
SAPpar1 = InStr(SAPrq, "%")
If SAPpar = 1 Then
SAPnwk = Mid(SAPrq, 3)
xy = Getbam(SAPnwk)' this is a function that talks to SAP and it works on first loop
End If
End if
End While
Next
I tried adding setting infinitecounter = 2 before the next statement and adding an if statement to reset the listener but failed.
In my ASP.NET(VB) project, I am facing error to get XML response from remote server using TcpClient. The error is Thread was being aborted. The code in which I am facing error is given as follows.
Private Function GetCMSAPIXMLResp(ByVal strReqXml As String, ByVal strAPIIpAddr As String, ByVal strAPIPort As String) As String
Dim strRespXml As String = String.Empty
Try
objClientSocket = New TcpClient()
objClientSocket.Connect(strAPIIpAddr, strAPIPort)
If objClientSocket.Connected = True Then
objNetStrm = objClientSocket.GetStream()
Dim btOutStrm() As Byte = System.Text.Encoding.ASCII.GetBytes(strReqXml)
objNetStrm.Write(btOutStrm, 0, btOutStrm.Length)
objNetStrm.Flush()
If objNetStrm.CanRead Then
Dim lngBuffSize As Long = CLng(objClientSocket.ReceiveBufferSize)
Dim btInStream(lngBuffSize) As Byte
strbldRespXml = New StringBuilder()
Dim iNoBytesRead As Integer = 0
Do
iNoBytesRead = objNetStrm.Read(btInStream, 0, btInStream.Length)
strbldRespXml.AppendFormat("{0}", System.Text.Encoding.ASCII.GetString(btInStream, 0, iNoBytesRead))
Loop While objNetStrm.DataAvailable
strRespXml = Convert.ToString(strbldRespXml)
strRespXml = strRespXml.Replace(vbCrLf, vbNullString)
Else
lblError.Text = "Unable to read"
End If
Else
lblError.Text = "Unable to connect with remote server"
End If
Catch ex As Exception
Throw
Finally
objClientSocket = Nothing
objNetStrm = Nothing
strbldRespXml = Nothing
End Try
Return strRespXml
End Function
Actually, I just want to know at what point the error is getting and Why.
NOTE : Port opening has been done and when I do ping and telnet to remote server, getting positive response.
So I was struggling with making head or tail out of the PayPal documentation and always felt that something was not right with my Webrequest.
So I stripped all the code back to basic and simply submitted the request via HTTP and the PLUS side is that I now get a response back from the PayPal sandbox server where ACK=Success and TOKEN=Valid-token-value-here there are some other variables returned too, such as CORRELATIONID and TIMESTAMP.
And hence so I tried some of the webrequest samples and I simply get a blank screen instead of being redirected to Paypal for the (sandbox) customer to complete payment.
So if anyone can post their WebRequest method that would be great.
Here is the code I used for my webrequest, I'm sure its wrong but cannot pinpoint where it is going wrong.
Also, when I run the code on my localhost during debugging, everything works fine and the call is completed with SUCCESS and a TOKEN is received.
When I run it live, I recieve Error Number 5 in the Error exception and also the text `Remote host failed to connect' in the STATUS DESCRIPTION.
THIS IS THE UPDATED CODE
Function MakeWebRequest(ByVal pUseSandbox As Boolean, ByVal pRequestMethod As String, ByVal pReturnUrl As String, ByVal pCancelUrl As String, ByRef pRtnStatus As String, ByRef pRtnStatusId As HttpStatusCode, ByRef pRtnResponseString As String) As Boolean
'
Dim _sxHost As String = Nothing
Dim _sxEndpoint As String = Nothing
Dim _sxNameValCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxResponseCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxCounta As Integer = Nothing
Dim _sxParamsString As String = Nothing
'
'-> Init
_sxParamsString = ""
MakeWebRequest = False
_sxNameValCol = New System.Collections.Specialized.NameValueCollection()
_sxResponseCol = New System.Collections.Specialized.NameValueCollection()
If pUseSandbox Then
_sxHost = "http://www.sandbox.paypal.com"
_sxEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
Else
_sxHost = "http://www.paypal.com"
_sxEndpoint = "https://api-3t.paypal.com/nvp"
End If
'-> Create Request
Try
'-> Key/Value Collection Params
_sxNameValCol.Add("METHOD", "SetExpressCheckout")
_sxNameValCol.Add("USER", _UserName)
_sxNameValCol.Add("PWD", _Password)
_sxNameValCol.Add("SIGNATURE", _Signature)
_sxNameValCol.Add("PAYMENTREQUEST_0_AMT", Format(_Basket.BasketTotalIncDelivery / 100, "0.00"))
_sxNameValCol.Add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale")
_sxNameValCol.Add("PAYMENTREQUEST_0_CURRENCYCODE", "GBP")
_sxNameValCol.Add("RETURNURL", pReturnUrl)
_sxNameValCol.Add("CANCELURL", pCancelUrl)
_sxNameValCol.Add("REQCONFIRMSHIPPING", "0")
_sxNameValCol.Add("NOSHIPPING", "2")
_sxNameValCol.Add("LOCALECODE", "EN")
_sxNameValCol.Add("BUTTONSOURCE", "PP-ECWizard")
_sxNameValCol.Add("VERSION", "93.0")
'-> UrlEncode
For _sxCounta = 0 To _sxNameValCol.Count - 1
If _sxCounta = 0 Then
_sxParamsString = _sxParamsString & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
Else
_sxParamsString = _sxParamsString & "&" & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
End If
Next
'-> Credentials (not used)
'_sxRequest.Credentials = CredentialCache.DefaultCredentials
Try
Dim _sxRequest As WebRequest = DirectCast(System.Net.WebRequest.Create(_sxEndpoint), System.Net.HttpWebRequest)
'-> Convert request to byte-array
Dim _sxByteArray As Byte() = Encoding.UTF8.GetBytes(_sxParamsString)
_sxRequest.Method = "POST" 'Our method is post, otherwise the buffer (_sxParamsString) would be useless
_sxRequest.ContentType = "application/x-www-form-urlencoded" 'We use form contentType, for the postvars
_sxRequest.ContentLength = _sxByteArray.Length 'The length of the buffer (postvars) is used as contentlength
Dim _sxPostDataStream As System.IO.Stream = _sxRequest.GetRequestStream() 'We open a stream for writing the postvars
_sxPostDataStream.Write(_sxByteArray, 0, _sxByteArray.Length) 'Now we write, and afterwards, we close
_sxPostDataStream.Close() 'Closing is always important!
'-> Create Response
Dim _sxResponse As HttpWebResponse = DirectCast(_sxRequest.GetResponse(), HttpWebResponse)
'-> Get Response Status
pRtnStatus = _sxResponse.StatusDescription
pRtnStatusId = _sxResponse.StatusCode
'-> Reponse Stream
Dim _sxResponseStream As Stream = _sxResponse.GetResponseStream() 'Open a stream to the response
'-> Response Stream Reader
Dim _sxStreamReader As New StreamReader(_sxResponseStream) 'Open as reader for the stream
pRtnResponseString = _sxStreamReader.ReadToEnd() 'Read the response string
MakeWebRequest = True
'-> Tidy up
_sxStreamReader.Close()
_sxResponseStream.Close()
_sxResponse.Close()
_sxByteArray = Nothing
_sxPostDataStream = Nothing
_sxRequest = Nothing
_sxResponse = Nothing
_sxResponseStream = Nothing
_sxStreamReader = Nothing
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "response(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "request(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
'-> Tidy Up
_sxHost = Nothing
_sxEndpoint = Nothing
_sxNameValCol = Nothing
_sxResponseCol = Nothing
_sxCounta = Nothing
_sxParamsString = Nothing
'
End Function
OK, so it's now clear that you're not getting any response from the server because your server isn't able to connect to PayPal's servers at all. Hence, you got no server-response and the message Unable to connect to the remote server. When I tested, I got a HTTP 200 response with the following body:
TIMESTAMP=2015-07-07T09:07:39Z&CORRELATIONID=7f4d2313c9696&ACK=Failure&VERSION=93.0&BUILD=17276661&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
Obviously that's because I tested with a blank username and password.
So, something is wrong with your server setup that's preventing you from making outside connections, either at the IIS level or due to your firewall configuration.
Without physically being present at your machine, there's not a lot we can do to track down what's blocking it, but you can try opening HTTP requests to other public websites like Google.com and see if those succeed.
I have a website where a user can choose to view a video (no copyright) that is on a 3rd party website. From the moment the user choose it, it needs to be downloaded onto my web server before the user can access it. I tried to automatically start the download on the 3rd party website and make a response.redirect with this path, but when the user is watching the video, if the video has only 10 seconds downloaded, any player/browser will considere this video as a ten-seconds video and stop it after 10 seconds.
What would be the best practice to redirect a stream instead of a file?
I found that this piece of code is doing exactly what I want. It downloads a file on a third party website, and as it's streaming it, each chunk is writen in the Response so that it completely obsfuscates the origin. Thus, it is possible to serve any file from any website as if I own it.
Private Sub SendFile(ByVal url As String)
Dim stream As System.IO.Stream = Nothing
Dim bytesToRead As Integer = 10000
Dim buffer() As Byte = New Byte((bytesToRead) - 1) {}
Try
Dim fileReq As System.Net.WebRequest = CType(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
Dim fileResp As System.Net.HttpWebResponse = CType(fileReq.GetResponse, System.Net.HttpWebResponse)
If (fileReq.ContentLength > 0) Then
fileResp.ContentLength = fileReq.ContentLength
End If
stream = fileResp.GetResponseStream
Dim resp As System.Web.HttpResponse = HttpContext.Current.Response
resp.ContentType = "application/octet-stream"
resp.AddHeader("Content-Disposition", ("attachment; filename=\""" + ("mp3" + "\""")))
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString)
Dim length As Integer = 1000000
While (length > 0)
If resp.IsClientConnected Then
length = stream.Read(buffer, 0, bytesToRead)
resp.OutputStream.Write(buffer, 0, length)
resp.Flush()
buffer = New Byte((bytesToRead) - 1) {}
Else
length = -1
End If
End While
Catch
stream.Close()
Finally
If (Not (stream) Is Nothing) Then
stream.Close()
End If
End Try
Response.End()
End Sub
I am using ZipOutputStream to get files from db, compress to zip and download (zip file around 400mb).
During this, my app pool memory is going up to 1.4gb and after download is complete, its coming down to 1gb when it should come back to like 100 mb or something.
There are only like 10 users using this app and only 1 user using this particular page.
i am calling the dispose method. I aslo tried explictly calling GC.Collect but still no use.
Am i missing anything here?
Thanks in advance.
Dim zipStream = New ZipOutputStream(HttpContext.Current.Response.OutputStream)
Try
da.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
Try
Dim docName As String = ""
strImgID = dr("image_id")
If Not IsDBNull(dr("loan_number")) Then iLoanID = dr("loan_number")
If Not IsDBNull(dr("document_name")) Then docName = dr("document_name")
Dim ext As String = dr("image_type_extension")
Dim strFinalFileName As String = ""
strFinalFileName = docName & "_" & iLoanID & ext
Dim b As Byte() = dr("image_binary")
Dim fileEntry = New ZipEntry(Path.GetFileName(strFinalFileName))
zipStream.PutNextEntry(fileEntry)
zipStream.Write(b, 0, b.Length)
Catch ex As Exception
LogError(ex, iLoanID & "," & strImgID)
AddError(sb, ex, iLoanID & "," & strImgID)
End Try
Next
Catch ex As Exception
Throw
Finally
zipStream.Close()
zipStream.Dispose()
cmd.Connection.Close()
cmd.Connection.Dispose()
End Try
You need to chunk data into the stream rather than allocate all at once.
E.g. (in c#)
byte[] buffer = new byte[4096];
FileStream readFs = File.OpenRead(strFile);
for (int rnt = readFs.Read(buffer, 0, buffer.Length);
rnt > 0;
rnt = readFs.Read(buffer, 0, buffer.Length))
{
zipoutputstream.Write(buffer, 0, rnt);
}
I think this will help with your memory issue. Please comment back if not..