Reputation: 11
im writing a simple Client/Server application in C#. as you see there is if(cSocket.Connected) tag in the codes, i want something like that... if a cSocket disconnected... i will give the codes, you can understand my problem from the title and my explanation...
Here is the code;
Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener sSocket = new TcpListener(System.Net.IPAddress.Any, 3162);
int Counter = 0;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n >> Server Started!");
sSocket.Start();
while (true)
{
Socket cSocket = sSocket.AcceptSocket();
NetworkStream NetworkStr = new NetworkStream(cSocket);
BinaryReader bReader = new BinaryReader(NetworkStr);
BinaryWriter bWriter = new BinaryWriter(NetworkStr);
IPEndPoint remoteIpEndPoint = cSocket.RemoteEndPoint as IPEndPoint;
if (cSocket.Connected)
{
Counter = Counter + 1;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n >> Client Connected! ~ Total: " + Counter + " ~ [" + remoteIpEndPoint + "]");
bWriter.Write("\n >> Server Says: You Connected to Me!");
}
}
}
}
Thanks for your helps :)
Upvotes: 1
Views: 280
Reputation: 1754
As Opi saied something like this will do it(It is from another Answer in StackOverFlow):
public static bool SocketConnected(Socket s)
{
if (!s.Connected) return false;
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 & part2)
return false;
return true;
}
Upvotes: 0
Reputation: 1308
I'm not that familiar with .NET things but in theory applications and protocols (including TCP/IP) have some kind of timeout to wait for. Like in the TCP/IP protocol family one side waits for the another for a certain amount of time after sending a package and if he doesn't get an answer he tries again and/or closes the connection after some time.
In short you can send a small request periodically and check if the client answers.
Upvotes: 1