I have the following code:
...
namespace ba = boost::asio;
...
ba::ip::tcp::resolver resolver(ioService);
ba::ip::tcp::socket sock(ioService);
ba::ip::tcp::resolver::query query(the_ip, the_port);
ba::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ba::ip::tcp::resolver::iterator end;
boost::system::error_code error = ba::error::host_not_found;
while (error && (endpoint_iterator != end))
{
sock.close();
sock.connect(*endpoint_iterator++, error);
}
When the server is up, it connects instantly and the rest of the code flows wonderfully, but when the server is offline or unreachable this while takes forever to exit.
Before the while: 09:04:37
When it exits: 09:05:40
Since I give query ONE IP and ONE PORT, shouldn't it exit instantly, given no connection can be established?
Are there any parameters I didn't configure? Something like "try X times" or "try for Y seconds"?
EDIT:
As seen in the comments, the problem seems to be a search on the internet, but the connection is local! (192.168...)
Why does it search the internet for a local IP?
As #MartinJames said on the comments:
"The internet is quite big, and has all sorts of links, some with very high latency.
Determining unreachability therefore takes a long time.
That is what happens when you connect all the computers on a planet together."
I tried disconnecting from the internet and the while exited instantly.
But the IP I'm using is local (192.168...), so this is still strange.
Thanks, man.
Related
I'm working on .NET Windows Form App which uses Google Cloud Firestore as Database. I've created functions (using Google.Cloud.Firestore NuGet Package functions) to read/write database documents. Everything working greatly but if app doesn't use any of this read/write functions more than 2-3 minutes, i'm getting this error: Grpc.Core.RpcException: 'Status(StatusCode="Unknown", Detail="Stream removed" But if uses read/write functions every 1-2 minutes, i do not get this error in short period. I can create a thread function to keep my database connection active but it causes unnecessary reads or writes. How can i solve it?
To Reproduce Error
string Path = AppDomain.CurrentDomain.BaseDirectory + #"AdminSDKName.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
FirestoreDb DataBase = FirestoreDb.Create("DatabaseID");
Query QRef = DataBase.Collection("CollectionID").Document("DocID").Collection("CollectionID").WhereEqualTo("isTrue", false);
QuerySnapshot snap = await QRef.GetSnapshotAsync();
Console.WriteLine(snap.Count.ToString());
Console.WriteLine("Waiting for 5 minutes..");
Task.Delay(300000).Wait();
Console.WriteLine("Waited for 5 minutes");
snap = await QRef.GetSnapshotAsync();
Console.WriteLine(snap.Count.ToString());
Console.WriteLine("Done without any error.");
I get error after "Waited for 5 minutes" line.
Update
If i connect my computer network to mobile phone network i do not get any error.
I have a feeling you're seeing a part of Firestore's connection management here. If that's indeed what we're seeing, the connection should be reestablished when needed and there's nothing you can change about this through the API.
A solution would be to find out what is closing the stream prematurely. The configuration of Grpc.Core to send a keepalive packet once a minute can be found in the Github.
I suggest you try the code on a few different networks if you can, keeping everything else the same, to see if you can identify what is closing the connection.
Please refer to the User guide.
If this does not resolve, update your question with minimal reproducible code.
I am using matlab to communicate with several machines.
I am trying to connect with LCC25 (Liquid crystal retarder controller made by Thorlabs) using usb b to usb a cable.
I made a code like this.
clear all; clc;
%%
ss=serial('COM7','BaudRate',9600,'DataBits',8);
set(ss,'Parity','none');
set(ss,'Terminator','LF');
fopen(ss);
fprintf(ss,'*idn?');
aa=fscanf(ss)
fclose(ss)
Then I get "Warning : Unsuccessful read : A timeout occurred before the Terminator was reached aa=="
Is there any problem in my code?
I am also interested in buying the LCC25 and controlling it with MATLAB, so this is very interesting for me and I would love to find out whether it works...
To debug your code, I am wondering what happens when you comment out everything but:
ss=serial('COM7','BaudRate',9600,'DataBits',8);
set(ss,'Parity','none');
set(ss,'Terminator','LF');
fopen(ss);
Since then we can now if the problem is in establishing the connection itself (which you should not run every time btw!), or in trying to send a command to the device...
If the object creation is succesful, you should see something like this:
Serial Port Object : Serial-COM4
Communication Settings
Port: COM7
BaudRate: 9600
Terminator: 'LF'
Communication State
Status: closed
RecordStatus: off
Read/Write State
TransferStatus: idle
BytesAvailable: 0
ValuesReceived: 0
ValuesSent: 0
Then you can try to add run
fopen(ss)
fscanf(ss)
in a seperate file, and see what the output is. If all of this works, you can start to try sending commands using the 'fprintf' command, but make sure not to run the 'serial' and 'fopen' command every
I am wondering where you obtained the command string '*idn?', did you find this in the help file? The same for the terminator 'LF', are you sure this is the correct terminator to use for the LCC25? When reading the error message you received, I suspect the problem to be that you might need to use other terminators, such as 'CR'.
I asked how to make TCP server that send data all the time in here: Julia TCP select and it works great. I now I have new problem, so I thought to start new conversation.
I did this kind of connection like on the picture:
So Sender sends sometimes something to server 1 and server 1 reads it and updates what to send to server 2 and Server 2 calculates numbers and communicates with C program.
Here is my server 1 code:
notwaiting = true
message = zeros(10,14)
server = listen(5001)
connection = connect(5003)
while true
if notwaiting
notwaiting = false
# Runs accept async (does not block the main thread)
#async begin
sock = accept(server)
reply= read(sock, Float64, 11)
message[:,convert(Int64,reply[1])] = reply[2:11]
write(connection,reshape(message,140))
global notwaiting = true
end
end
write(connection,reshape(message,140))
if message[1,1] == -1.0
close(connection)
close(server)
break
end
sleep(0.01) # slow down the loop
end
Sender is:
Connection2= connect(5001)
message = [2.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0]
write(Connection2,message)
close(Connection2)
And server 2 is like this:
function Server2_connection()
println("Waiting for connection")
server2 = listen(5003)
conn_2 = accept(server2)
while isopen(conn_2)
try
message_server2 = round(read(conn_2,Float64,140),3)
ins_matrix = reshape(message_server2[1:140],10,14)
catch e
println("caught an error $e")
break
end
end
println("Connection closed")
close(conn)
close(server)
end
The problem is that everything together is really heavy. I mean that I can send 2 messages from sender and everything is running really slow. I can run the whole thing 10-15s and then it freezes. All the connections work, but really slowly. My question is am I missing something or have something that makes the servers really slow? How can I code this better way?
I don't have anymore problem with slowness. I got help from julia-users google forum and on of them(Tanmay K. Mohapatra) wrote better code for same purpose: https://gist.github.com/tanmaykm/c2ab61a52cc5afa0e54fe61905a48ef1 It works
same way.
One problem with both codes is that they don't close connections properly. If server 2 goes down, the server 1 gets writing error and server 1 stays in listen mode.
Other ways it works. Thanks to Tanmay!
Edit: found the slower....the thing what should slow things down, did it. The sleep command did slow things down, but it slowed down more than I expected. If I had sleep variable 0.001 seconds, it will slow down the whole system like 0.014s. So I removed sleep command and it works fine.
I am trying to implement something using the NMSSH framework in swift.
To not have my UI freeze while collecting data from the servers I put everything inside a
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))
And I sometimes (about 50% probability) randomly get one of these errors. I am not sure what causes them or how to prevent them. The appear seemingly randomly, but in chains, one it goes wrong it will keep going wrong for a while, and when it finally works it will work a few times in a row.
Socket connection to 192.168.178.27 on port 22 failed with reason -2, trying next address...
Error Domain=libssh2 Code=-18 "Authentication failed (keyboard-interactive)" UserInfo={NSLocalizedDescription=Authentication failed (keyboard-interactive)}
Error Domain=libssh2 Code=-9 "Waiting for password response" UserInfo={NSLocalizedDescription=Waiting for password response}
but most frequently
Error Domain=libssh2 Code=-9 "Would block requesting userauth list" UserInfo={NSLocalizedDescription=Would block requesting userauth list}
and
Error Domain=libssh2 Code=-9 "Would block" UserInfo={NSLocalizedDescription=Would block}
EDIT: I pasted my whole code here, but it is kinda messy.
The function is supposed to be called once and then check a bunch of servers for their availability.
getServers() returns an array of dictionaries, each looking like ["alias": "iMac", "ip":" mac.local", "port":"22", "username": "root", "password": "123"]
Try using NSOperationQueue, it is higher level and might be able to handle that better
I have an intermittent problem with a telnet based server on Unix (the problem crops up on both AIX and Linux).
The server opens two sockets, one to a client telnet session, and one to a program running on the same machine as the server. The idea is that the data is passed through the server to and from this program.
The current setup has a loop using select to wait for a "read" file descriptor to become available, then uses select to wait for a "write" file descriptor to become available.
Then the program reads from the incoming file descriptor, then processes the data before writing to the outgoing descriptor.
The snippet below shows what is going on. The problem is that very occasionally the read fails, with errno being set to ECONNRESET or ETIMEDOUT. Neither of these are codes documented by read, so where are they coming from?
The real question is, how can I either stop this happening, or handle it gracefully?
Could doing two selects in a row be the problem?
The current handling behaviour is to shut down and restart. One point to note is that once this happens it normally happens three or four times, then clears up. The system load doesn't really seem to be that high (it's a big server).
if (select(8, &readset, NULL, NULL, NULL) < 0)
{
break;
}
if (select(8, NULL, &writeset, NULL, NULL) < 0)
{
break;
}
if (FD_ISSET(STDIN_FILENO, &readset)
&& FD_ISSET(fdout, &writeset))
{
if ((nread = read(STDIN_FILENO, buff, BUFFSIZE)) < 0)
{
/* This sometimes fails with errno =
ECONNRESET or ETIMEDOUT */
break;
}
}
Look at the comments in http://lxr.free-electrons.com/source/arch/mips/include/asm/errno.h on lines 85 and 98: these basically say there was a network connection reset or time out. Check and see if there are timeouts you can adjust on the remote network program, or send some periodic filler bytes to ensure that the connection stays awake consistently. You may just be victim of an error in the network transit path between the remote client and your local server (this happens to me when my DSL line hiccups).
EDIT: not sure what the downvote is for. The man page for read explicitly says:
Other errors may occur, depending on the object connected to fd.
The error is probably occuring in the select, not in the read: you're not checking errors after the select, you're just proceeding to the read, which will fail if the select returned an error. I'm betting if you check the errno value after the select call you'll see the errors: you don't need to wait for the read to see the errors.