I am trying to make an aSync connection to a server using TcpClient.BeginConnect, but am encountering some difficulties. This is my first time using Tcp so please bear with me.
The connection itself works fine when the server is running, i can send and receive messages without problem. However when I stop the server and try to connect to it, Tcp.BeginConnect will pretend it is actually connected to a server without returning an error, until i try to actually send data which will obviously fail.
When i use TcpClient.Connect() instead it'll return A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. when no connection is established after a few seconds, letting me know the connection failed.
Is there a way to get this same behaviour with TcpClient.BeginConnect? Or am I doing something wrong myself?
i looked around and found C# BeginConnect callback is fired when not connected which is somewhat similair and the answer was that EndConnect had to be called in the callback before the socket becomes usuable, but i'm already doing that.
my code:
public static void OpenTcpASyncConnection()
{
if (client == null)
{
client = new TcpClient();
IAsyncResult connection = client.BeginConnect(serverIp, serverPort, new AsyncCallback(ASyncCallBack), client);
bool succes = connection.AsyncWaitHandle.WaitOne();//returns true
if (!succes)
{
client.Close();
client.EndConnect(connection);
throw new Exception("TcpConnection::Failed to connect.");
}
else
{
Debug.LogFormat("TcpConnection::Connecting to {0} succeeded", serverIp);
}
}
else
{
Debug.Log("TcpConnection::Client already exists");
}
}
public static void ASyncCallBack(IAsyncResult ar)
{
Debug.Log("Pre EndConnect");
client.EndConnect(ar);
Debug.Log("Post EndConnect");//this never gets called?
}
the boolean succes is true even if the server is offline (or does this always return true as long as the operation finishes?), thus i assume it thinks it is actually connected, and the Debug.Log after client.EndConnect(ar) never gets called. Not a single error gets returned.
In summary; Am I forgetting something/doing something wrong? or is this expected behaviour?
Edit: language is C# with the .net 3.5 framework. It is ment for a Unity application though i'm not inheriting from monobehaviour for this. If you require any additional information I will try to provide this.
Kind regards and thanks for your time,
Remy.
Related
I'm writing a Connect-Four game in C#, and now want to include the possibility to play games online using TCP. Each instance of the game exe should work as both a server, in order to listen to incoming game invitations, and a client, to send said invitations. Of course, only one at a time is important.
I have read and watched a few C# tutorials on this (namely Jeff Chastine's tutorial 22) and I understand the basics of network communication. After getting past a few permission-errors, fixed by executing as administrator, I am now running into two issues.
1) When I try connecting from a machine on the same network, I always get an error saying the desired server did not respond to the request. When I enter the debugger, the program is stuck at the .AcceptTcpClient call (as if no connection has been attempted). I understand that this is a blocking call, but the code should continue when a connection is attempted. I have not tried connecting two machines in different networks, as I have only one network available.
2) This one is a rather minor issue regarding threading: even though I call listenerThread.Abort() when I close the application, the thread does not stop. I do not have too tight a grip on threads in C#, so I assume this problem is a rather easy fix.
Initialisation of listener and listenerThread
listenerThread = new Thread(ListenForInvites);
listener = new TcpListener(Dns.Resolve("localhost").AddressList[0], setting.port);
client = new TcpClient();
The method for listening to incoming connections
private void ListenForInvites()
{
try
{
listener.Start();
TcpClient enemyClient = listener.AcceptTcpClient(); // the call where it gets stuck even if someone connects
onlineSr = new StreamReader(enemyClient.GetStream());
onlineSw = new StreamWriter(enemyClient.GetStream());
onlineSw.WriteLine($"ACCEPT {player.name} {player.color.R} {player.color.G} {player.color.B}"); // I am using my own protocol, not HTTP (no clue if this is a horrible idea)
HandleConnection().Wait();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error");
}
}
The method for attempting the connection
public void SendInvite(string ip)
{
try
{
string[] ipSplit = ip.Split(':');
client.Connect(ipSplit[0], Convert.ToInt16(ipSplit[1]));
onlineSr = new StreamReader(client.GetStream());
onlineSw = new StreamWriter(client.GetStream());
onlineSw.WriteLine($"INVITE {player.name} {player.color.R} {player.color.G} {player.color.B}"); // player is an instance variable
onlineSw.Flush();
HandleConnection().Wait();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Fehler");
}
}
What am I doing wrong? Any help is appreciated.
I'm trying to educate myself on the intricacies of reading from a NetworkStream, and understanding the various ways in which problems can occur. I have the following code:
public async Task ReceiveAll()
{
var ns = this.tcp.GetStream();
var readBuffer = new byte[1000];
while (true)
{
int bytesRead;
try
{
bytesRead = await ns.ReadAsync(readBuffer, 0, readBuffer.Length);
if (bytesRead == 0)
{
// Remote disconnection A?
break;
}
}
catch (IOException)
{
// Remote disconnection B?
break;
}
catch (ObjectDisposedException)
{
// Local disconnection?
break;
}
/*Do something with readBuffer */
}
}
I've marked three points in the code where the program says 'something has gone awry, there is no point continuing'.
The 'Local disconnection' isn't exactly something wrong, it will happen when I locally close the socket which is the only way to exit the loop under normal circumstances. I don't think anything else can cause this, so I think I'm safe to just swallow the exception.
The two 'Remote disconnection' points are what I'm not sure about. I know ReadAsync will return 0 if the connection is terminated remotely (A), but the IOException also seems to fire in some circumstances. If my remote client is a C# console, then closing the socket seems to make 'A' happen, and closing the console window seems to be make 'B' happen. I'm not sure I understand what the difference is between these scenarios?
Finally, a bit of a general question, but is there anything glaringly wrong with this bit of code or my above assumptions?
Thanks.
EDIT: In response to my use of ObjectDisposedException to abort out of the loop:
This is what my 'Stop' method looks like (from the same class as above):
public void Stop()
{
this.tcp.Close();
}
This causes the pending 'ReadAsync' to except with ObjectDisposedException. AFAIK there isn't any other way to abort this. Changing this to:
public void Stop()
{
this.tcp.Client.Shutdown(SocketShutdown.Both);
}
Doesn't appear to actually do anything to the pending call, it just continues waiting.
When NetworkStream returns 0, this means that the socket has received a disconnect packet from the remote party. This is how network connections are supposed to end.
The correct way to shut down the connection (especially if you are in a full-duplex conversation) is to call socket.Shutdown(SocketShutdown.Send) and give the remote party some time to close their send channel. This ensures that you receive any pending data instead of slamming the connection shut. ObjectDisposedException should never be part of the normal application flow.
Any exceptions thrown indicate that something went wrong, and I think it's safe to say you can no longer rely on the current connection.
TL;DR
I don't see anything wrong with your code, but (especially in full-duplex communication) I'd shut down the send channel and wait for a 0-byte packet to prevent receiving ObjectDisposedExceptions by default:
use tcp.Shutdown(SocketShutdown.Send) to tell the remote party you want to disconnect
your loop may still receive data that the remote party was sending
your loop will, if everything went right, then receive a 0-byte packet, indicating that the remote party is disconnecting
loop terminates the right way
you may want to decide to dispose the socket after a certain amount of time, if you haven't received the 0-byte packet
I've tried checking the server:port with telnet and I'm getting the expected results. So either writer.Write() or reader.ReadLine() isn't working cause I get nothing from the server.
TcpClient socket = new TcpClient(hostname, port);
if (!socket.Connected) {
Console.WriteLine("Failed to connect!");
return;
}
TextReader reader = new StreamReader(socket.GetStream());
TextWriter writer = new StreamWriter(socket.GetStream());
writer.Write("PING");
writer.Flush();
String line = null;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
Console.WriteLine("done");
EDIT: I might have found the issue. This code was based off examples I found on the web. I tried another irc server: open.ircnet.net:6669 and I got a response:
:openirc.snt.utwente.nl 020 * :Please wait while we process your connection.
It seems as if I probably need to run the reader in a Thread so it can just constantly wait for a response. However it does seem weird that the program got caught on the while loop without ever printing done to the console.
I think you need to provide further details. I'm just going to assume that because you can easily telnet to the server using the same port your problem lies in the evaluation of the Connected property...
if (!socket.Connected) {
Console.WriteLine("Failed to connect!");
return;
}
this is wrong because Microsoft clearly specifies in the documentation that the Connected property is not reliable
Because the Connected property only reflects the state of the connection as of the most recent operation, you should attempt to send or receive a message to determine the current state. After the message send fails, this property no longer returns true. Note that this behavior is by design. You cannot reliably test the state of the connection because, in the time between the test and a send/receive, the connection could have been lost. Your code should assume the socket is connected, and gracefully handle failed transmissions.
That said, you should not use this property to determine the state of the connection. Needless to say that using this property to control the flow of your console app will result in unexpected results.
Suggestion
Remove the evaluation of the Connected property
Wrap your GetStream and Write method calls in a try/catch block to handle network communication errors
reader.ReadLine() will just wait for any data to arrive. If no data arrive, it seems to hang. That's a feature of tcp (I don't like it either). You need to find out how the end of the message is defined and stop based on that end criterion. Be careful, the end of message identifier may be split into two or more lines...
RFC for ping says that the server may not respond to it & such connections has to be closed after a time. Please check the RFC: https://www.rfc-editor.org/rfc/rfc1459#section-4.6.2
I have a metro app talking to a device over wifi using UDP. However, when I disconnect the device from the network or start the app with the device disconnected, nothing happens. ConnectAsync doesn't throw an exception, the app doesn't throw an exception, the app runs like nothing's wrong.
I can't ping the other end but If I give it a formatted string it will respond. The device is currently connected to a router which has internet access but I'm eventually planning to use a router without internet access. I've never done anything with UDP so I'm at a loss here.
Here is an implementation of a UDP listener/writer(taken from Pete Bright at 10rem.net)
class Network
{
private DatagramSocket _socket;
public bool IsConnected { get; set; }
public bool recieved;
public string ret;
public Network()
{
IsConnected = false;
_socket = new DatagramSocket();
_socket.MessageReceived += OnSocketMessageReceived;
}
public async void Connect(HostName remoteHostName, string remoteServiceNameOrPort)
{
try
{
await _socket.ConnectAsync(remoteHostName, remoteServiceNameOrPort);
}
catch (Exception e)
{
var msg = new MessageDialog(e.ToString());
msg.ShowAsync();
}
IsConnected = true;
}
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
var reader = args.GetDataReader();
var count = reader.UnconsumedBufferLength;
var data = reader.ReadString(count);
ret = data.Trim();
recieved = true;
}
DataWriter _writer =null;
public async void SendMessage(string message)
{
if (String.IsNullOrEmpty(message)) return;
if (_writer == null)
{
var stream = _socket.OutputStream;
_writer = new DataWriter(stream);
}
_writer.WriteString(message);
await _writer.StoreAsync();
}
}
UDP Sockets are "connection-less", so the protocol does not know anything about whether or not the server and client are connected. To know if a a connection is still "active" you will have to implement your own connection detection.
I might recommend reading beej's guide to sockets. It's a good read and pretty funny:
http://beej.us/guide/bgnet/
As it was said, there is no concept like there is in tcp/ip with sync/ack, etc to communicate back and forth and ensure something is there.
Clients are neither connected nor disconnected, only listening or sending really.
So with that said you need to implement a receive timeout from the client.
There are some funny jokes with UDP, since you send data and just essentially fling it out into space. The order the packets are received can't matter either or you are stuck implementing your own scheme here as well.
What you'll need to do here is actually try to reach the device. If you care, then you can do this every X seconds.
As it is stated here: How to test a remote UDP Port
(keep with me, a better approach below this but wanted to provide multiple means)
You can use UdpClient, set a receive timeout on the underlying socket,
make a connection to that remote server/port, Send some small message
(byte[] !) and call Receive.
IF the port is closed you get an exception saying that the connection
was forcibly closed (SocketException with
ErrorCode 10054 = WSAECONNRESET)... which means the port is NOT open.
However- I think a better approach is to actually agree upon a protocol id or some specific data that the clients send every X seconds. If received, then update your 'client connected' table, otherwise consider them disconnected until the client sends a packet with a protocol id over.
A great series on this that you can probably easily adapt to c# is at:
http://gafferongames.com/networking-for-game-programmers/virtual-connection-over-udp/
I believe your code above can be refactored as well to only Send() to an address rather than connect, since there really is no true connect.
To help out people that stumble upon this:Apparently my google-fu is pretty weak. This shows how to set timeouts for TCP and UDP sockets. Default behavior is to never time out(which is consistent with what I saw).
Edit: It doesn't work. Even with a timeout of 500ms I'm still seeing the same behavior of "no exception thrown".
I'm trying to reuse a socket in an asynchronous HTTP client, but I'm not able to connect to the host the second time around. I basically treat my asynchronous HTTP client as a state machine with the following states:
Available: the socket is available for use
Connecting: the socket is connecting to the endpoint
Sending: the socket is sending data to the endpoint
Receiving: the socket is receiving data from the endpoint
Failed: there was a socket failure
Clean Up: cleaning up the socket state
In the connecting state I call BeginConnect:
private void BeginConnect()
{
lock (_sync) // re-entrant lock
{
IPAddress[] addersses = Dns.GetHostEntry(_asyncTask.Host).AddressList;
// Connect to any available address
IAsyncResult result = _reusableSocket.BeginConnect(addersses, _asyncTask.Port, new AsyncCallback(ConnectCallback), null);
}
}
The callback method changes the state to Sending once a successful connection has been established:
private void ConnectCallback(IAsyncResult result)
{
lock (_sync) // re-entrant lock
{
try
{
_reusableSocket.EndConnect(result);
ChangeState(EClientState.Sending);
}
catch (SocketException e)
{
Console.WriteLine("Can't connect to: " + _asyncTask.Host);
Console.WriteLine("SocketException: {0} Error Code: {1}", e.Message, e.NativeErrorCode);
ThreadPool.QueueUserWorkItem(o =>
{
// An attempt was made to get the page so perform a callback
ChangeState(EClientState.Failed);
});
}
}
}
In the cleanup I Shutdown the socket and Disconnect with a reuse flag:
private void CleanUp()
{
lock (_sync) // re-entrant lock
{
// Perform cleanup
if (_reusableSocket.Connected)
{
_reusableSocket.Shutdown(SocketShutdown.Both);
_reusableSocket.Disconnect(true);
}
ChangeState(EClientState.Available);
}
}
Subsequent calls to BeginConnect result in a timeout and an exception:
SocketException: A connection attempt
failed because the connected party did
not properly respond after a period of
time, or established connection failed
because connected host has failed to
respond XX.XXX.XX.XX:80
Error Code: 10060
Here is the state trace:
Initializing...
Change State: Connecting
Change State: Sending
Change State: Receiving
Change State: CleanUp
Callback: Received data from client 0 // <--- Received the first data
Change State: Available
Change State: Connecting // <--- Timeout when I try to reuse the socket to connect to a different endpoint
What do I have to do to be able to reuse the socket to connect to a different host?
Note: I have not tried to re-connect to the same host, but I assume the same thing happens (i.e. fails to connect).
Update
I found the following note in the documentation of BeginConnect:
If this socket has previously been disconnected, then BeginConnect must be called on a thread that will not exit until the operation is complete. This is a limitation of the underlying provider. Also the EndPoint that is used must be different.
I'm starting to wonder if my issue has something to do with that... I am connecting to a different EndPoint, but what do they mean that the thread from which we call BeginConnect must not exit until the operation is complete?
Update 2.0:
I asked a related question and I tried using the "Async family" calls instead of the "Begin family" calls, but I get the same problem!!!
I commented on this question: what is benefit from socket reuse in C# about socket reuse using Disconnect(true)/DisconnectEx() and this may help you.
Personally I think it's an optimisation too far in client code.
Re update 1 to your question; no, you'd get an AbortedOperation exception if that were the case (see here: VB.NET 3.5 SocketException on deployment but not on development machine) and the docs are wrong if you're running on Vista or later as it doesn't enforce the "thread must exist until after overlapped I/O completes" rule that previous operating systems enforce.
As I've already said in the reply to the linked question; there's very little point in using this functionality for outbound connection establishment. It's likely that it was originally added to the Winsock API to support socket reuse for AcceptEx() on inbound connections, where, on a very busy web server that was using TransmitFile() to send files to clients (which is where disconnect for reused seems to have originated). The docs state that it doesn't play well with TIME_WAIT and so using it for connections where you initiate the active close (and thus put the socket into TIME_WAIT, see here) doesn't really make sense.
Can you explain why you think this micro optimisation is actually necessary in your case?
have you checked the MaxConnections Setting?
http://msdn.microsoft.com/de-de/library/system.servicemodel.nettcpbinding.maxconnections.aspx