Loopback connection always refused in C# [closed] - c#

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've just spent two days on this. This is run in the game engine Unity3D, but that shouldn't make a difference. These two lines ALWAYS fail:
TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15219));
The error I get is:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0
at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in <filename unknown>:0
at StreamIn.Connect (System.String server, System.String message) [0x00011] in C:\XXX\StreamIn.cs:41
UnityEngine.Debug:Log(Object)
StreamIn:uPrint(String) (at Assets/StreamIn.cs:27)
StreamIn:Connect(String, String) (at Assets/StreamIn.cs:77)
StreamIn:Start() (at Assets/StreamIn.cs:18)
I've tried everything, including changing my firewall settings and disabling the firewall.
I get the same error with a dummy IP address.
If I try port 80 instead of 15219, the Unity editor freezes. (I do have a web server running.)
Am I missing something obvious? Or not obvious?

I always find it useful to sanity check these things with a different network tool outside of my .NET code. I think hercules is great for this as you can easily open up a tcp server for you app to connect to, and/or test a connection from a client perspective.

Related

C# issue connecting to MySQL Linux Database

It's the first time I'm using PuTTY + dedicated Linux Server.
I have installed the MySQL server client on my dedicated Linux server:
apt-get install mysql-server
After installing, I had to set the MySQL Server password, which is what I did.
I have then created a database and a table, which I inserted one row into.
CREATE DATABASE frag_huans;
use frag_huans;
CREATE TABLE hero_data (
-> ID int(2),....);
INSERT INTO hero_data VALUES ('1',...);
this is literally all I have done so far in regards to PuTTY.
What I now tried to achieve, was connecting to the database via my C# Class (in Unity3D).
I've done this with my localhost (xampp) server and it worked fine.
string constr = "Server=localhost;Database=letzter;User ID=root;Password=;Pooling=true";
Now I wanted to connect to the Linux MySQL database the same way:
string constr = "Server=myServerIP;Database=frag_huans;Uid=root#serverIP;Pwd=myPassword";
where "myServerIP" is definitely my servers IP and the Uid is the ID that gets shown in PuTTY at the start of the command line.
The connection won't set up, Unity debugger prompting:
MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts. ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0
at System.Net.Sockets.Socket+Worker.Connect () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at MySql.Data.MySqlClient.NativeDriver.Open () [0x00000] in <filename unknown>:0
at MySql.Data.MySqlClient.Driver.Open () [0x00000] in <filename unknown>:0
at MySql.Data.MySqlClient.Driver.Create (MySql.Data.MySqlClient.MySqlConnectionStringBuilder settings) [0x00000] in <filename unknown>:0
at MySql.Data.MySqlClient.MySqlPool.CreateNewPooledConnection () [0x00000] in <filename unknown>:0
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection () [0x00000] in <filename unknown>:0
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver () [0x00000] in <filename unknown>:0
UnityEngine.Debug:Log(Object)
HeroDB:Awake() (at Assets/Preload/HeroDB.cs:51)
Using another value at "Server=..." tells me that the host can't be found which ensures me that my host address seems to be correct.
I have also tried to create another "user" for the MySQL Server + grant this one all privileges:
CREATE USER fh#myServerIP IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES on frag_huans.* to fh#myServerIP;
FLUSH PRIVILEGES;
Changing the connection string to the user shown above didn't change the outcome.
I believe that the Linux server/MySQL database blocks my access. Is there any privileges I have to set to the connection? What could be a possible cause for this problem? I've seen many people having the "No connection could be made because the target machine actively refused it" - issue, but there seem to be too many different cases.
If you can help me in any way, I would be very happy
Thanks in advance, Cshaprest
Try below commands from client machine # telnet <serverip> 3306
If first point fails, Check if there is Firewall rule to accept all incoming mysql connections on port 3306.
Server accept connections from all ip's if mysql id binded to 0.0.0.0 check it in /etc/my.cnf
It's just for confirmation , I assume you have added client IP[not the server IP] in below user creation command.
GRANT ALL PRIVILEGES on frag_huans.* to fh#myclientServerIP;
FLUSH PRIVILEGES;

Mono - attempt to close TCP connection, thread hangs, connection gets stuck in CLOSE_WAIT

We have a situation where a server running mono 4.2.2 4.4 on Linux receives multiple incoming TCP connections from clients. It also maintains a single outgoing TCP connection to another system, and regularly makes HTTP REST requests to yet another system. After an arbitrary length of time, the server grinds to a halt - the number of connections shoots up and then drops off (see graph below), thread dumps show large numbers of connections, predominantly the incoming connections from clients, stuck trying to shut down (see stack trace below). Running netstat on the server shows a large number of connections stuck in CLOSE_WAIT.
As far as we can tell, the sudden increase in connections doesn't correspond to an actual sudden surge in load - new connections are actually balanced across 2 instances of the server on two different machines, and the other machine carries on happily. The other server does see quite a rise in connections in the few minutes after the first fails, but this is to be expected after one server has become unresponsive, and the rise is much more gradual, over the course of minutes rather than a sudden spike.
"Threadpool worker" at <unknown> <0xffffffff>
at (wrapper managed-to-native) System.Threading.WaitHandle.WaitOne_internal (System.Threading.WaitHandle,intptr,int,bool) <0xffffffff>
at System.Threading.WaitHandle.WaitOne () <0x0005c>
at System.Net.Sockets.Socket.EndSend (System.IAsyncResult,System.Net.Sockets.SocketError&) <0x0006f>
at System.Net.Sockets.Socket.EndSend (System.IAsyncResult) <0x0002b>
at System.Net.Sockets.NetworkStream.EndWrite (System.IAsyncResult) <0x00057>
at Mono.Security.Protocol.Tls.RecordProtocol.EndSendRecord (System.IAsyncResult) <0x000dc>
at Mono.Security.Protocol.Tls.RecordProtocol.SendRecord (Mono.Security.Protocol.Tls.ContentType,byte[]) <0x00037>
at Mono.Security.Protocol.Tls.RecordProtocol.SendAlert (Mono.Security.Protocol.Tls.Alert) <0x0009f>
at Mono.Security.Protocol.Tls.RecordProtocol.SendAlert (Mono.Security.Protocol.Tls.AlertDescription) <0x0004b>
at Mono.Security.Protocol.Tls.SslStreamBase.Dispose (bool) <0x0008b>
at Mono.Security.Protocol.Tls.SslServerStream.Dispose (bool) <0x00017>
at System.IO.Stream.Close () <0x00019>
at Mono.Security.Protocol.Tls.SslStreamBase.Close () <0x00014>
at System.IO.Stream.Dispose () <0x00013>
at (wrapper remoting-invoke-with-check) System.IO.Stream.Dispose () <0xffffffff>
at System.Net.Security.SslStream.Dispose (bool) <0x00037>
at System.IO.Stream.Close () <0x00019>
at CompanyName.Networking.Connection.Close () <0x00057>
at CompanyName.Networking.Connection.ProcessBytes (int) <0x00202>
at CompanyName.Networking.Connection.DataReceivedAsync (System.IAsyncResult) <0x0006f>
at (wrapper runtime-invoke) <Module>.runtime_invoke_void__this___object (object,intptr,intptr,intptr) <0xffffffff>
at <unknown> <0xffffffff>
at (wrapper managed-to-native) System.Runtime.Remoting.Messaging.AsyncResult.Invoke (System.Runtime.Remoting.Messaging.AsyncResult) <0xffffffff>
at System.Runtime.Remoting.Messaging.AsyncResult.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () <0x0000c>
at System.Threading.ThreadPoolWorkQueue.Dispatch () <0x001d6>
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () <0x00008>
at (wrapper runtime-invoke) <Module>.runtime_invoke_bool (object,intptr,intptr,intptr) <0xffffffff>
Only three lines of the stacktrace are in our code. Given that they are DataReceivedAsync -> ProcessBytes -> Close, this means that the earlier stream.BeginRead has triggered the callback we give it (DataReceivedAsync), which calls EndRead and finds that 0 bytes have been read. This causes ProcessBytes to conclude that the TCP connection has been closed by the other end, and it calls our Close() method, which calls Close() on the SslStream and the TcpClient. Looking at the stacktrace, the Close() call on the SslStream is where we're getting stuck.
The usual response to "why is my connection stuck in CLOSE_WAIT?" is "you need to close the connection". However, we're attempting to close the connection and finding that the framework code hangs on a WaitHandle. How can we resolve this issue?

Timeout Exception: Calling Soap API from Within a REST API

I have a very odd problem. I have a REST API that uses ServiceStack that does a few things like save payment data etc. From within that API I start building payment object so I can fire off a payment to a Payment Gateway. This payment gateway is a Soap API Using SoapHttpClientProtocol.
The problem I am having is that the Soap API Times out. I have a stack trace that lead me to believe it is happening inside the framework somewhere.
System.Net.WebException: Error: ConnectFailure (Connection timed out) ---> System.Net.Sockets.SocketException: Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0
at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequest.GetRequestStream () [0x00000] in <filename unknown>:0
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke (System.String method_name, System.Object[] parameters) [0x00000] in <filename unknown>:0
Above is the exception I got so I believe it is happening inside the Invoke method. Here is the code which is in the proxy file.
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("paymenturl", RequestNamespace="gatewayurl", ResponseNamespace="gatewayurl", ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped, Use=System.Web.Services.Description.SoapBindingUse.Literal)]
public string SubmitPayment(string trnXML) {
object[] results = this.Invoke("SubmitPayment", new object[] {
trnXML});
return ((string)(results[0]));
}
Does anyone know why this would happen?
Now the SOAP Payment API works though the UI. So if call it straight from the UI I can make a payment and get a successful response back. When I do it from the API it doesn't work.
Is this perhaps a Architectural problem which does not allow an API call from within another API?
Has anyone come across anything like this before?
Any help will appreciated.
Found the problem. It was because there was a mono.security.dll in my bin folder. This is not needed apparently so removed it. Once I did that it worked.
Credit goes to this Post: Mono Apache2 HttpWebRequest crashes with "The request timed out"

HttpWebRequest NameResolutionFailure exception in .NET (with Mono on Ubuntu)

I have a .NET program running on Ubuntu via Mono 2.10
The program downloads a webpage via an HttpWebRequest every minute or so which works fine most of the time:
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
using (objResponse = objRequest.GetResponse())
{
using (StreamReader sr =
new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
}
The problem is that after few days I start getting exceptions thrown:
DateTime: 01/25/2012 08:15:41
Type: System.Net.WebException
Error: Error: NameResolutionFailure
Stack:
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0
at System.Net.HttpWebRequest.GetResponse () [0x00000] in <filename unknown>:0
at socks_server.Program.readHtmlPage (System.String url) [0x00000] in <filename unknown>:0
at socks_server.Program.getAccessKeysProc () [0x00000] in <filename unknown>:0
The server is still abel to resolve DNS, for example
wget http://www.google.com
Will return the file without any probelm as will ping and other commands that resolve DNS.
My program however will continue to throw that exception until I restart it. After restarting the application it will start working again as it should.
I have checked open file counts on the system (400 ish), memory usage (327mb of 4gb), CPU usage (2-3%) and all are OK.
Any ideas?
You can solve it by translating the host name to ip and add the host name to Headers collection or to Host property.
If your url is http://example.com/uri. Resolve the host yourself. Suppose its 1.2.3.4. It'll be http://1.2.3.4/uri. Now add Host: example.com header to your request. I think it can be done by setting HttpWebRequest.Host property.
I know this is an old post, but was facing the same error, so thought to share the solution.
The best solution I found, when that exception occurs while the Wifi
is connected, is just to retry my server call with a slight sleep in
between. It works most of the time, otherwise if the second call
fails I cancel the request.
This error can also raise if the user's Wifi is very unstable or the
signal is very low. The same error occurs if there is no internet
connection at all, even if connected to Wifi.
This is in line with my ans on :
System.Net.WebException: Error: NameResolutionFailure when Calling WCF Services throwing exception in mono android application
Well I use the HttpClient - but it might be a similar problem. I had the same issue on a Android device (it worked on a Windows Phone)... But after I added the Host to the header it worked!
client.DefaultRequestHeaders.Host = "mydomain.com";
You can still use the name in the url (you don't have to use the IP address)
I was experiencing the same issue in my mono application on raspbian. I've tried different solutions described in this and other threads but none worked. Eventually, I was able to fix the problem by changing the name servers in /etc/resolv.conf to the google ones https://developers.google.com/speed/public-dns/
Mirko
I was getting this error when I started the mobile app (android or iOS it does not matter) without internet connection. After restored the connection every request returns "NameResolutionFailure exception". I had to wait 120 seconds for having the http request working again. Setting the following line of code anywhere in the app startup the error was finally gone.
System.Net.ServicePointManager.DnsRefreshTimeout = 0;
The default DnsRefreshTimeout value is 120 seconds.

Subject<T> stops publishing items

I have a Subject<T> that I'm publishing items into via OnNext and after a while, under load, I get this exception:
System.NullReferenceException: Object reference not set to an instance of an object
at System.Diagnostics.ExceptionExtensions.PrepareForRethrow (System.Exception exception) [0x00000] in <filename unknown>:0
at System.Concurrency.AsyncLock.Wait (System.Action action) [0x00000] in <filename unknown>:0
at System.Concurrency.Scheduler+<>c__DisplayClass4.<Schedule>b__0 () [0x00000] in <filename unknown>:0
at System.Concurrency.ImmediateScheduler.Schedule (System.Action action) [0x00000] in <filename unknown>:0
at System.Concurrency.Scheduler.Schedule (IScheduler scheduler, System.Action`1 action) [0x00000] in <filename unknown>:0
at System.ScheduledObserver`1[GetNotifyd.Superfeedr.FeedItem].EnsureActive () [0x00000] in <filename unknown>:0
at System.Collections.Generic.Subject`1[GetNotifyd.Superfeedr.FeedItem].OnNext (GetNotifyd.Superfeedr.FeedItem value) [0x00000] in <filename unknown>:0
After this happens I can still publish items via OnNext, but my subscriber no longer receives anything. This is running under mono 2.10.1 using the .NET 3.5 Reactive Extensions DLLs from MS (i.e. i don't think it's mono code that's dying). I haven't seen this happen when I try it on windows, but i haven't run the same loads there. The item that is the argument to OnNext is definitely not null, so that's not the cause.
Any idea what might be causing this or how i could recover the Subject, or do i just have to create a new Subject, notify all my subscribers to subscribe to that instead?
Since it looks like an Rx issue, i've also reported it on their forum
Update: The issue was confirmed as a Rx/mono issue for the combinations of versions i was using. Upgrading to latest Rx (1.0.10605) fixed the problem.
You might be hitting a race condition bug in Rx.
Notice in this MSDN thread, a poster had a similar problem: an unexplained NullReferenceException coming from a stack trace that hits AsyncLock.Wait.
Now, his problem was caused by [ThreadStatic] not working on the Windows Phone 7. Is it possible [ThreadStatic] has nuanced behavior on Mono?
I'd recommend reporting this error to the Rx team via the Rx forums.

Categories

Resources