C
C#•4mo ago
stn

SocketException, TCPListener, TCPClient reason?

a) Why do I get a SocketException when opening a TCPListener + TCPClient @ IP 127.0.0.1, Port 5089 (there is only my listener at that port, and only my client sends on it) telling me the system actively refused the connection - however it still goes through and sends everything/gets received?! and the firewall didn't block it b) what information to look at to know such stuff?
62 Replies
Buddy
Buddy•4mo ago
Port is in use Doesn't have to be your socket Did you try changing port? Or use 0 as port 0 meaning it will use a random available port
stn
stnOP•4mo ago
port isn't in use, since there's only my 1 server and my 1 client
Buddy
Buddy•4mo ago
Any application on your computer can use the port it doesn't have to be your program
stn
stnOP•4mo ago
Nothing uses the port but these 2 programs - says netstat
Buddy
Buddy•4mo ago
And what happens if you change the port as previously mentioned? say to 0 so it uses a random available port
stn
stnOP•4mo ago
changing the port didn't help, tried multiple very crazy ones or actually tried several that were ok in netstat
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
stn
stnOP•4mo ago
wait I don't use IIS/IIS Express, my original intention for using the TCPClient was just to be able to save some Diagnostic data to disk from a SourceGenerator - which sadly have an Analyzer Rule that prohibits usage of IO and the File- / Path-Namespaces during their activities. [which makes it a bit hard to debug their work] I give you the code in a sec
stn
stnOP•4mo ago
Pastebin
using System;using System.Diagnostics;using System.Net;using System...
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin
Client - Pastebin.com
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
stn
stnOP•4mo ago
nope, no firewall because it actually works the send works, but I get an exception every time I do it additionally my firewall hasn't had anything in the blocked log + I found out when the server is configured to use port 0 - this is when the connection won't work (since server port = 0, client port != 0, the connection fails and that is the only time that the exception ever gets caught in my catch (Socketexception ex), clientside the other times when the server is set correctly and when the connection actually works but yet excepts... it doesn't get caught
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
333fred
333fred•4mo ago
which sadly have an Analyzer Rule that prohibits usage of IO and the File- / Path-Namespaces during their activities
Correct. These things are verbotten. Do not use them
stn
stnOP•4mo ago
back ok I know, but does this relate to the error I'm getting?
Unknown User
Unknown User•4mo ago
Message Not Public
Sign In & Join Server To View
stn
stnOP•4mo ago
it doesn't matter what he says, because there's an analyzer rule that shows you an Error that prevents compilation when you use System.IO or System.IO.Path but it doesn't do so when using the networkstack there's no interference with the network stack to be true the one thing has nothing to do with the other so what they don't want is you spawning your own sourcecode files when using the sourcegenerator, that must have been the initial idea
333fred
333fred•4mo ago
@sharwell, this is another thing we apparently need to block
stn
stnOP•4mo ago
of blocking IO
333fred
333fred•4mo ago
I cannot say this strongly enough: do not do IO Network calls are IO
stn
stnOP•4mo ago
to be true
333fred
333fred•4mo ago
Do not use it We do not want you doing any kind of IO
sharwell
sharwell•4mo ago
IO, in general, will not work
stn
stnOP•4mo ago
I tried to use the AnalyzerConfigOptions , ..
var options = context.AnalyzerConfigOptions.GlobalOptions;
if (options.TryGetValue("build_property.MyCustomProperty", out var myValue))
{
context.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor(
"GEN001",
"Source Generator",
$"Value from MSBuild: {myValue}",
"Generator",
DiagnosticSeverity.Warning,
true)));
}
var options = context.AnalyzerConfigOptions.GlobalOptions;
if (options.TryGetValue("build_property.MyCustomProperty", out var myValue))
{
context.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor(
"GEN001",
"Source Generator",
$"Value from MSBuild: {myValue}",
"Generator",
DiagnosticSeverity.Warning,
true)));
}
but it didn't work, I couldn't get the diagnostic outside using the steps described
sharwell
sharwell•4mo ago
what do you mean "couldn't get the diagnostic outside"?
stn
stnOP•4mo ago
(wherever that was, i suppose microsoft.com) well I don't remember what the goal was whether it was spawning a file or printing it to console or something else I cannot remember but it clearly didn't work, then I went for writing my TCP client / sv that's the big deal? I know this is not a good procedure, since you state, whenever IO happens during SourceGenerators' activities - you cannot guarantee the correct execution and random stuff might happen
333fred
333fred•4mo ago
If you're trying to troubleshoot an analyzer, write a unit test Much easier, more repeatable
stn
stnOP•4mo ago
no I am not trying to trouble shoot an analyzer
333fred
333fred•4mo ago
And at the end, you have tests
stn
stnOP•4mo ago
I tried to trouble shoot my own code in the sourcegen
333fred
333fred•4mo ago
Then why are you putting IO in your source generator?
stn
stnOP•4mo ago
because I cannot use the Debugger inside it?! and the Diagnostic didn't do whatever it was supposed to i'm afraid
333fred
333fred•4mo ago
Why do you think you can't debug your source generator? That's what tests are for
stn
stnOP•4mo ago
because it didn't stop on any breakpoints
333fred
333fred•4mo ago
Did you write a unit test?
stn
stnOP•4mo ago
nope
333fred
333fred•4mo ago
Then... what were you expecting?
sharwell
sharwell•4mo ago
once you write a unit test, you can debug the test and it will stop at breakpoints
stn
stnOP•4mo ago
since when do you have to write unit-tests to be able to debug VS compilation/compiled runtime
sharwell
sharwell•4mo ago
that's not the way we look at it writing unit tests is so easy and so reliable for debugging analyzers and source generators that all the work on looking at other approaches became irrelevant basically there is nothing left to gain. it works as close to perfect as anyone could want
stn
stnOP•4mo ago
why do you enforce the usage of unit-tests
333fred
333fred•4mo ago
Everyone, and I mean everyone, reacts the same way to our suggestions to write unit tests. With visceral denial. And by the time they're done, almost everyone agrees it was the right approach There are a couple here and there that still disagree. But almost everyone does not
stn
stnOP•4mo ago
thank you for enlightening me regarding the UnitTest. and yet, does anyone of you two smart people, have an idea what the answer to my actual question is? : a) Why do I get a SocketException when opening a TCPListener + TCPClient @ IP 127.0.0.1, Port 5089 (there is only my listener at that port, and only my client sends on it) telling me the system actively refused the connection - however it still goes through and sends everything/gets received?! and the firewall didn't block it b) what information to look at to know such stuff?
sharwell
sharwell•4mo ago
what question was that? 1) IO behavior is undefined. SocketException is allowed. Not having a SocketException is also allowed.
stn
stnOP•4mo ago
in regard of 1) ok, what if I repeat it without a sourcegen and the same thing happens?
sharwell
sharwell•4mo ago
then it would be a question for dotnet/runtime, different team
stn
stnOP•4mo ago
undefined I guess means you're using a not-thread-safe-way of parallel task processing? is that correct? (thread safe for invocation of external code)
sharwell
sharwell•4mo ago
undefined means you cannot infer anything about the behavior
stn
stnOP•4mo ago
well, but why is it undefined?
sharwell
sharwell•4mo ago
because we chose to not attempt to define or support it it's fairly common in compiler work to leave things as undefined as soon as we define it, it becomes a guarantee that we have to preserve basically forever
stn
stnOP•4mo ago
Pasteboard - Uploaded Image
Simple and lightning fast image sharing. Upload clipboard images with Copy & Paste and image files with Drag & Drop
stn
stnOP•4mo ago
see, I unloaded all sourcegenerator projects, and removed any code that depended on that and yet I get the same message
sharwell
sharwell•4mo ago
I have no experience with that API
stn
stnOP•4mo ago
it has nothing to do with the API, I can show you what happens: 1/3: Program.Main:
public static void Main(string[] args)
{
try
{
MsgSender.SendLogMessage($"Started.").Wait();
Console.WriteLine($"Started.");
Console.ReadKey();
}
catch (SocketException ex)
{
D.W("SocketException ---> "+ ex.ToString() + $"{ex.ErrorCode} SocketErrorCode: {ex.SocketErrorCode} Inner:{ex.InnerException} ");

}
catch(Exception ex ) {
D.W($"{ex}");
}
}
public static void Main(string[] args)
{
try
{
MsgSender.SendLogMessage($"Started.").Wait();
Console.WriteLine($"Started.");
Console.ReadKey();
}
catch (SocketException ex)
{
D.W("SocketException ---> "+ ex.ToString() + $"{ex.ErrorCode} SocketErrorCode: {ex.SocketErrorCode} Inner:{ex.InnerException} ");

}
catch(Exception ex ) {
D.W($"{ex}");
}
}
2/3: Client:
public class MsgSender
{
public static MsgMode Mode = MsgMode.TCP;
public static int Port = 7334;
public static async Task SendLogMessage(string msg)
{
await Task.Delay(500);
switch (Mode) {
case MsgMode.TCP: {
try {
await SendTcpMsg(msg).ConfigureAwait(false);
}
catch (SocketException ex) {
// this should now catch any socket-related exceptions
Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
D.W($"SocketException: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine(".." +ex);
}

break;
}
case MsgMode.NamedPipe:
{
SendNamedPipeMsg(msg);

break;
}
}
}
public class MsgSender
{
public static MsgMode Mode = MsgMode.TCP;
public static int Port = 7334;
public static async Task SendLogMessage(string msg)
{
await Task.Delay(500);
switch (Mode) {
case MsgMode.TCP: {
try {
await SendTcpMsg(msg).ConfigureAwait(false);
}
catch (SocketException ex) {
// this should now catch any socket-related exceptions
Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
D.W($"SocketException: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine(".." +ex);
}

break;
}
case MsgMode.NamedPipe:
{
SendNamedPipeMsg(msg);

break;
}
}
}
[NoDebug]
private async static Task SendTcpMsg(string msg)
{
await Task.Delay(100);
try
{
// Ensure all connection and stream activities are inside the try-catch
using (TcpClient client = new TcpClient("localhost", Port))
{
Console.WriteLine($"Sending Message: {msg}");

client.NoDelay = true;

byte[] data = Encoding.UTF8.GetBytes(msg);
using (NetworkStream stream = client.GetStream())
{

stream.Write(data, 0, data.Length);
//stream.Close(); // Close the stream explicitly
}



await Task.Delay(10);
}
}
catch (SocketException ex)
{
// this should now catch any socket-related exceptions
Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
D.W($"SocketException: {ex.Message}");
}
catch (IOException ex)
{
// catch any IO exceptions, e.g., from stream handling issues
Console.WriteLine($"IOException: {ex.Message}");
D.W($"IOException: {ex.Message}");
}
catch (Exception ex)
{
// catch any other exceptions
Console.WriteLine($"Error: {ex.Message}");
D.W($"Error: {ex.Message}");
}
}
[NoDebug]
private async static Task SendTcpMsg(string msg)
{
await Task.Delay(100);
try
{
// Ensure all connection and stream activities are inside the try-catch
using (TcpClient client = new TcpClient("localhost", Port))
{
Console.WriteLine($"Sending Message: {msg}");

client.NoDelay = true;

byte[] data = Encoding.UTF8.GetBytes(msg);
using (NetworkStream stream = client.GetStream())
{

stream.Write(data, 0, data.Length);
//stream.Close(); // Close the stream explicitly
}



await Task.Delay(10);
}
}
catch (SocketException ex)
{
// this should now catch any socket-related exceptions
Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
D.W($"SocketException: {ex.Message}");
}
catch (IOException ex)
{
// catch any IO exceptions, e.g., from stream handling issues
Console.WriteLine($"IOException: {ex.Message}");
D.W($"IOException: {ex.Message}");
}
catch (Exception ex)
{
// catch any other exceptions
Console.WriteLine($"Error: {ex.Message}");
D.W($"Error: {ex.Message}");
}
}
3/3 Server:
public class Program
{

public static void Main()
{
Console.WriteLine($"Opening TCP Server @ {TCPServer.Port}");
TCPServer.CreateTCPServer();

Console.ReadKey();
}
}


public class TCPServer
{
private static bool isRunning = true;
public static int Port = 7334;

public static void CreateTCPServer()
{
TcpListener server = new TcpListener(IPAddress.Loopback, Port);
try
{ server.Start();
Console.WriteLine($"Server started (Port:{Port})...");
while (isRunning)
{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected...");
Task.Run(async () => await HandleClient(client));
}
}
catch (Exception ex) { Debug.WriteLine($"EX: {ex}"); }
finally { server.Stop(); Console.WriteLine("Server stopped."); }
}
private async static Task HandleClient(TcpClient client
public class Program
{

public static void Main()
{
Console.WriteLine($"Opening TCP Server @ {TCPServer.Port}");
TCPServer.CreateTCPServer();

Console.ReadKey();
}
}


public class TCPServer
{
private static bool isRunning = true;
public static int Port = 7334;

public static void CreateTCPServer()
{
TcpListener server = new TcpListener(IPAddress.Loopback, Port);
try
{ server.Start();
Console.WriteLine($"Server started (Port:{Port})...");
while (isRunning)
{
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client connected...");
Task.Run(async () => await HandleClient(client));
}
}
catch (Exception ex) { Debug.WriteLine($"EX: {ex}"); }
finally { server.Stop(); Console.WriteLine("Server stopped."); }
}
private async static Task HandleClient(TcpClient client
private async static Task HandleClient(TcpClient client)
{
try
{
await using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead;

while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead).Trim();
Console.WriteLine($"MSG: {message}");

// write msg 2 Log
await File.AppendAllTextAsync("D:\\Junction\\generator7.log", message + "\n");

// check: quit command?
if (message == "!q")
{
StopServer();
break; // Exit
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
}
finally
{
// Ensure the client connection is closed
client.Close();
Console.WriteLine("Client connection closed.");
}
}


// stop the server
public static void StopServer()
{
Console.WriteLine("Shutdown command received. Stopping the server...");
isRunning = false;
}
private async static Task HandleClient(TcpClient client)
{
try
{
await using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead;

while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead).Trim();
Console.WriteLine($"MSG: {message}");

// write msg 2 Log
await File.AppendAllTextAsync("D:\\Junction\\generator7.log", message + "\n");

// check: quit command?
if (message == "!q")
{
StopServer();
break; // Exit
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error handling client: {ex.Message}");
}
finally
{
// Ensure the client connection is closed
client.Close();
Console.WriteLine("Client connection closed.");
}
}


// stop the server
public static void StopServer()
{
Console.WriteLine("Shutdown command received. Stopping the server...");
isRunning = false;
}
sorry - just realized the last few lines were missing that's trivial code, I mean it should be possible to read it in discord and make assumptions @sharwell , @333fred
333fred
333fred•4mo ago
Like Sam, I don't have much experience with sockets
sharwell
sharwell•4mo ago
I won't be able to help with this as I'm not familiar with these APIs. I haven't done any network I/O in probably almost 10 years
stn
stnOP•4mo ago
me neither just this
stn
stnOP•4mo ago
it's absolutely trivial, I took the example from the Microsoft-page even for writing the client and the server https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/sockets/tcp-classes
Use TcpClient and TcpListener - .NET
Learn how to use the TcpClient class to create a socket to request and receive data using TCP in .NET.
333fred
333fred•4mo ago
I would close this thread and start over; just use your sample code above, and then hopefully someone who can actually help you will
stn
stnOP•4mo ago
so it was actually just a goto-quicker completed coding work?
333fred
333fred•4mo ago
This thread has too much cruft in it
stn
stnOP•4mo ago
because nobody could appear on the stage and say :) hey I have an error,... using IO and a sourcegen, right? to be fair, it's a good choice, since it prevents people from spawning actual sourcefiles then just tell me how to correctly use the diagnostic?
333fred
333fred•4mo ago
Let us know when you've written a unit test 🙂
stn
stnOP•3mo ago
actually I gave up on that project since then but it makes no sense for me to quickly hack something together and write a unit-test for ensuring it works correctly when I just want to try something out a Unit-Test,... that's what I write when I want to ensure it works forever so I see any issues in the CI So the answer was ... someone is running a Virtual Machine on my computer (and probably I am in a VM right now) - since after uninstalling the Hypervisor in Add/Remove Programs -> Windows Features -> []Hypervisor, reboot .... but doing /systeminfo still gives me 'A hypervisor has been detected.' closing/closed the post
Want results from more Discord servers?
Add your server