Sockets.receive stops receiving, while there is still data incoming - asp.net

I have to Transfer a string from an asp.net web application to a VB.NET Desktop application. The data is send completely but the receiving end stops after About 8 kB of Data. There is no error message, it just ignores the rest of the data.
The transferred string is a semicolon separated list of print instructions and data. Normally the string is around 1 to 1.5kb of size. But now we have to Transfer a customers signature as well. This "Blows" the data up to about 15kb on average.
We are working with System.Net.Sockets.Socket.
On my development System, Windows 10, it works fine. On older machines, Windows Server 2008-R2, our Clients machines, the data is cut short.
The Software is compiled with .Net 4.7.2 on the Web-App side and 4.5 on the Desktop side.
We traced the Transfer with Wireshark and it appears that the Receiver receives exactly 6 TCP Packages and then ignores the rest. There is no error message and no disconnect.
I've tried to Change the Send/Receive Parameters to include an error flag, but it is Always returned ok. Using Send/Receive without Parameters, produced the same results.
Send Code from the Website:
Try
remoteEP = New IPEndPoint(_ipAddress, _listenPort)
clientSocket.SendTimeout = 2000
clientSocket.Connect(remoteEP)
clientSocket.Send(Encoding.ASCII.GetBytes(dataString), 0,
Encoding.ASCII.GetBytes(dataString).Count,
SocketFlags.None, SendError)
Catch ex As Exception
log.Fatal("IP socket init. failed", ex)
Finally
clientSocket.Close()
End Try
Receive code from the Printer-App
//Wait for incoming Data
clientSocket = server.Accept
//Signal receiving state to the frontend.
setReceiving()
ReDim receivedBytes(100001)
//Wait a second to make sure everything has been transferred
Threading.Thread.Sleep(1000)
Dim SError As SocketError
clientSocket.ReceiveTimeout = 1000
Try
receivedBytesLength = clientSocket.Receive(receivedBytes, 0,
100001, SocketFlags.None, SError)
Catch ex As SocketException
log.Debug("startReceiver - ReceiveTimeout erreicht", ex)
End Try
I need all the data to be transferred or at least an error message, so I can work on the problem.

Related

Xamarin Android project cannot connect to localhost API

I have been working on this problem for quite some time. I've read the many similar posts and their solutions don't help me (many posts are old and stale). I have a new Xamarin project and a localhost API that I am testing to. Initially I installed our production API locally and it doesn't connect. So I created a smaller test API and have had varying results in connecting. Xamarin Android will not connect with a "Failed to connect to localhost:XXXXX" message. I built a WPF project and get the same results. However I can connect to outside public API's (github) with both. I can connect to my localhost with a Windows forms desktop app and successfully get & post. Postman and httprepl both connect locally and successfully get & post. A couple of the other things the other posts suggested are 1) Client handler to ignore SSL - doesn't work, 2) Use the emulator's browser to connect to localhost - cannot connect. (this might be exposing where the problem really is but not sure).
Also The debugger seems to be behaving oddly. When the debugger gets to the HttpResponseMessageresponse.... line it rarely makes it to the next line so I cannot inspect the statuscode. The block I have below is in a try/catch and rarely makes it to the catch if the connection truly fails. Sometimes it will be caught at the catch and that's how I get the "failed to connect" message. Another developer here has run the project on his computer and gets the same results/errors on his computer.
HttpResponseMessage response = await client.SendAsync(request);
var Statuscode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
var jsonbody = response.Content.ReadAsStringAsync().Result;
var ResponseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
else
{
string oops = "Nothing";
}
I seem to be running out of options and am looking for any advice.
Thanks in advance.

Question about pymodbusTCP server implementaion

We have a simulator(client) and controller(server).
The controller sends a command signal through ModbusTCP to the simulator.
I want to emulate this controller on my computer.
What I have done
For the test, I wrote pymodbus Server script on my pc and pymodbus Client script on another PC. There was no problem to read holding and input register from client pc.
I connected my clinet pc to controller(server) to know what kind of values I have to send to actual client(simulator). I found out that 8 registers(from 0 to 7) are used to store integer values.
I tried to establish a connection between my pc(sever) and simulator computer(client).I was able to establish a connection and send a response to the client.
Problem
I have no information about this client(simulator) because we have no access to the client script.
I found out that this client sends a request not only for the reading but also for writing.
When I use the holding register, I got an error "illegal data address." But the input register does not show any error. For this reason, I am using input_register to save a specific integer number.
I stored some values on input_register, but sever input_registers are written by client(simulator) as below.
write request from client(simulator)
polling server(pc) with modpoll software
Question
why write requests from the client(simulator) overwrite my input_register? As far as I know, input_register is used for only reading. I assume that I made a mistake in storing a variable on the input_register.
When I make a connection between controller and simulator, wireshark and modpoll show that client(simulator) reads registers (from 0 to 7). But when I make a connection between my server(pc) and client(simulator), my sever response with different register numbers as below. Resister number starts from 1000. Why does simulator request different register start number? ex) from 0: controller, from 1000: PC(sever)
First response from server(pc)
Update! my server can respond with the values but with wrong register numbers. I changed starting register number(0 -->1000).
I attached picture.
response from server(pc)
Please advice me on this issue.
I will do my best effort to solve this issue.
'''
from pymodbus.server.sync import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock, ModbusSparseDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.transaction import ModbusRtuFramer, ModbusBinaryFramer
#%%
import logging
FORMAT = ('%(asctime)-15s %(threadName)-15s'
' %(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s')
logging.basicConfig(format=FORMAT)
log = logging.getLogger()
log.setLevel(logging.DEBUG)
#%%
#%%
def run_server():
store = ModbusSlaveContext(
ir=ModbusSequentialDataBlock(0, [28692,28692,28692,28692,28692,65508,65508,65508
]),zero_mode=True)
context = ModbusServerContext(slaves=store, single=True)
StartTcpServer(context, address=("192.168.1.231", 502))
identity = ModbusDeviceIdentification()
identity.VendorName = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'
#%%
if __name__ == "__main__":
run_server()
'''
Dear MarcosG,
I attached screen-shots from wireshark as below.
write request from clinet(simulator)
- as you can see clinet(simulator) send a request for writing and register number start from 256.
read response from server(controller)
- Sever(controller) responds to the request of clinet for reading. And it send a respond and register number start from 256.
polling sever with modpoll software
- we can look the values on the registers of sever, as you can see, values are stored in the register from 0 to 7. These values are from controller lever. If I adjust lever, these values are changing.
requested address_exel_File
- We have one more simulator(bridge2). It shows the same register number with both controller(server) and pc(server).
problem: the actual registers of sever which store values are from 0 to 7. However, Client and server communicate with different registers (from 256) which contain "0" values. But there is no issue for adjusting parameters of ship on the simulator.
Best regards
Byeon Seongsu

Response.WriteFile function fails and gives 504 gateway time-out

Environment:
-SharePoint 2010 foundation
-Claim based authentication
-Execution time out in web.config is set to 3600
Overview:
We have an excel export functionality where we connect to AD and SQL databases to fetch Users and their related data for a perticular Organization Unit (OU)in Active Directory.
We have on OU in AD which has got around 1400 users in it. We are using Open and Closed xml to generate excel file which works fine and takes about 11-14 minutes to generate a file on the server on following path
C:\inetpub\wwwroot\wss\VirtualDirectories\VirtualDirectyrName\Excel\FileName.xlsx
Immediately after generating a file we have following piece of code which would read file from server and dump it on output steam and presents a file ope-save as dialog box in browser to end user.
Problem Description:
When an Organization has less number of users and it does not take more than 5-6 minteus to generate the file on server, following piece of code successfully downloads the file on browser. But when for above mentioned OU where we have 1400 users the reponse.writefile function fails and in browse we get to see 'Browse can not display this web page' (when fiddler was on we found it gives - http 504 error). Surpricingly if we perform this export from the server itself (i.e browse the web site on server) it downloads without issue.
protected void lnkbtnDownloadFile_Click(object sender, EventArgs e)
{
String fileName = #"C:\inetpub\wwwroot\wss\VirtualDirectories\VirtualDirectyrName\Excel\540KBFileWhichFails.xlsx";
//File size is hardly ~500 KB
//Wait for around 12 minutes, to mimic a scenario of file generation which takes time on staging and prod. environment.
System.Threading.Thread.Sleep(720000);
try
{
if (fileName != "")
{
var file = new FileInfo(fileName);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
Response.Write("This file does not exist.");
}
}
catch (Exception ex)
{
//This would usually give thread aboart exception but thats expected.
}
}
we dont see any error in ULS logs, event logs specific to this behavior.
Please note , response.TransmitFile also gives same behaviour.
any idea ?
What I suspect here is that you have felt on session lock. What I mean is that the download and the generation and all this calls made using the session, and session locks everything until finish.
To solve this issue do two thinks.
When you generate this file, generate it ether with thread ether with handle with out session needed
Download this file from a handler (that not use session) and not from the page post back.
For example you make a handler, eg download.ashx and you make a link to your page as download.ashx?thisfileId=7723423&SecurityID=82jkj1288123 Inside your handler you read this parameters and you send the file. But if you make this on the page then a way is to disable the session for this page if you not use session, for example you set EnableSessionState="false" on the first line declarations.
Some similar questions and session relative answer.
call aspx page to return an image randomly slow
Replacing ASP.Net's session entirely
How to deliver big files in ASP.NET Response?
I figured out the issue, It was an issue with the Idle time out issue in the Hardware load balancer we where using. Default value in load balancer was 0 which meant 11 minutes and my file generation was taking longer than that which caused this issue. Increasing load balancer idle time out issue seems to be solutions.

Getting 2032 error (On only 1 machine)

I built an AIR app a while ago. One of the users today got a new machine (XP) and keeps getting a 2032 error when the app tries to send/receive data via HTTPService I verified that this page works when accessed within a web browser. It also works on AIR apps on other machines. The page and the AIR app haven't been changed for months, the only thing that has changed is this particular users computer. I recompiled to get a more specific error and this is what I got:
(mx.messaging.messages::ErrorMessage)#0
body = ""
clientId = "DirectHTTPChannel0"
correlationId = "B38588EC-AEA0-84F0-F5B2-F6B6AB6C3456"
destination = ""
extendedData = (null)
faultCode = "Server.Error.Request"
faultDetail = "Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032" errorID=2032]. URL: https://www.example.com/mypage.php"
faultString = "HTTP request error"
headers = (Object)#1
DSStatusCode = 0
messageId = "2BC38D14-63DD-345E-50DD-F6B6AEE75438"
rootCause = (flash.events::IOErrorEvent)#2
bubbles = false
cancelable = false
currentTarget = (flash.net::URLLoader)#3
bytesLoaded = 0
bytesTotal = 0
data = ""
dataFormat = "text"
errorID = 2032
eventPhase = 2
target = (flash.net::URLLoader)#3
text = "Error #2032"
type = "ioError"
timestamp = 0
timeToLive = 0
As I am writing this I had the user restart and relaunch the application, it is now working so I am not too worried about it, but I am still curious what could have happened if anyone has any ideas?
Update
Today (next day) It is happening again and restart isn't even fixing it today. It has to be something on her machine interfering causing the problem because I can run the program on any other machine just fine with no problem. Not sure what it could be or how to troubleshoot that?
Did the server hiccup just then, i.e. downtime and/or cosmic ray? Cross reference the user access time with the apache access/error.log on the server. Did crossdomain.xml change anyplace that your program references?
I had somewhat the same problem here but with a Flash (Web - Flex 4.1 SDK) application.
after trying out a huge assortment of solutions we narrowed we finally came up with one that works pretty reliably for all systems, including newly installed machines.
A. add global event listeners at the root (or stage) of the application, on flex preinitialize stage.
IOErrorEvent.IO_ERROR
IOErrorEvent.NETWORK_ERROR
HTTPStatusEvent.HTTP_STATUS
ErrorEvent.ERROR
SecurityErrorEvent.SECURITY_ERROR
if an error is cought - event.preventDefault();
B. add event listeners on every loader used in the App for the following errors:
IOErrorEvent.IO_ERROR
SecurityErrorEvent.SECURITY_ERROR
HTTPStatusEvent.HTTP_STATUS
*to attempt recovery, like falling back to an external interface call...
C. place all the SWZ files from the bin-release folder together with the SWF file in the same path on the server you use to deliver your App.
in my case these are the files needed:
sparkskins_4.5.1.21328.swz
spark_4.5.1.21328.swz
textLayout_2.0.0.232.swz
rpc_4.5.1.21328.swz
osmf_1.0.0.16316.swz
framework_4.5.1.21328.swz
* to discover this i used Chrome developer console to see which errors occur on the page and discovered a chain of 404s when the app tries to download these files.
D. have a properly configured crossdomain.xml policy file which includes the allow http request xml tag.
<allow-http-request-headers-from domain="*" headers="*"/>
replace the * as needed in your particular case.
Cheers

ORA-29270: too many open HTTP requests

Can someone help me with this problem that occurs whenever you run a TRIGGER, but works in a normal PROCEDURE?
TRIGGER:
create or replace
procedure testeHTTP(search varchar2)
IS
Declare
req sys.utl_http.req;<BR>
resp sys.utl_http.resp;<BR>
url varchar2(500);
Begin
url := 'http://www.google.com.br';
dbms_output.put_line('abrindo');
-- Abrindo a conexão e iniciando uma requisição
req := sys.utl_http.begin_request(search);
dbms_output.put_line('preparando');
-- Preparandose para obter as respostas
resp := sys.utl_http.get_response(req);
dbms_output.put_line('finalizando response');
-- Encerrando a comunicação request/response
sys.utl_http.end_response(resp);
Exception
When Others Then
dbms_output.put_line('excecao');
dbms_output.put_line(sys.utl_http.GET_DETAILED_SQLERRM());
End;
close your user session and then the problem is fixed.
Internal there is a limit from 5 http requests.
Might a problem is the missing: utl_http.end_response
or an exception in the app and not a close from the resp object.
modify the code like that:
EXCEPTION
WHEN UTL_HTTP.TOO_MANY_REQUESTS THEN
UTL_HTTP.END_RESPONSE(resp);
you need to close your requests once you are done with them, it does not happen automatically (unless you disconnect form the db entirely)
It used to be utl_http.end_response, but I am not sure if it is the same api any more.
Usually we need UTL_HTTP.END_RESPONSE(resp); to avoid of ORA-29270: too many open HTTP requests, but I think I reproduced the problem of #Clóvis Santos in Oracle 19c.
If web-service always returns status 200 (success) then too many open HTTP requests never happens. But if persistent connections are enabled and web-service returns status 404, behavior becomes different.
Let`s call something that always return 404.
First call of utl_http.begin_request returns normally and opens new persistent connection. We can check it with select utl_http.get_persistent_conn_count() from dual;. Second call causes an exception inside utl_http.begin_request and persistent connection becomes closed. (Exception is correctly handled with end_response/end_request).
If I continue then each odd execution returns 404 normally and each even execution gives an exception (handled correctly of course).
After some iterations I get ORA-29270: too many open HTTP requests. If web-service returns status 200 everything goes normally.
I guess, it happens because of the specific web-service. Probable it drops persistent connection after 404 and doesn't after 200. Second call tries to reuse request on persistent connection but it doesn't exist and causes request leak.
If I use utl_http.set_persistent_conn_support (false, 0); once in my session the problem disappears. I can call web-service as many times as I need.
Resolution:
Try to switch off persistent connection support. Probable, on the http-server persistent connections work differently for different requests. Looks like a bug.

Resources