Async tcp client and server. How can I determine that the client or the server is no longer available?

Hello. I would like to write async tcp client and server. I wrote this code but a have a problem, when I call the disconnect method on client or stop method on server. I can't identify that the client or the server is no longer connected.
I thought I will get an exception if the client or the server is not available but this is not happening.
private async void Process()
try
while (true)
var data = await this.Receive();
this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
catch (Exception exception)
How can I determine that the client or the server is no longer available?
Server
public class Server
private readonly Dictionary<IPEndPoint, TcpClient> clients = new Dictionary<IPEndPoint, TcpClient>();
private readonly List<CancellationTokenSource> cancellationTokens = new List<CancellationTokenSource>();
private TcpListener tcpListener;
private bool isStarted;
public event Action<string> NewMessage;
public async Task Start(int port)
this.tcpListener = TcpListener.Create(port);
this.tcpListener.Start();
this.isStarted = true;
while (this.isStarted)
var tcpClient = await this.tcpListener.AcceptTcpClientAsync();
var cts = new CancellationTokenSource();
this.cancellationTokens.Add(cts);
await Task.Factory.StartNew(() => this.Process(cts.Token, tcpClient), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
public void Stop()
this.isStarted = false;
foreach (var cancellationTokenSource in this.cancellationTokens)
cancellationTokenSource.Cancel();
foreach (var tcpClient in this.clients.Values)
tcpClient.GetStream().Close();
tcpClient.Close();
this.clients.Clear();
public async Task SendMessage(string message, IPEndPoint endPoint)
try
var tcpClient = this.clients[endPoint];
await this.Send(tcpClient.GetStream(), Encoding.ASCII.GetBytes(message));
catch (Exception exception)
private async Task Process(CancellationToken cancellationToken, TcpClient tcpClient)
try
var stream = tcpClient.GetStream();
this.clients.Add((IPEndPoint)tcpClient.Client.RemoteEndPoint, tcpClient);
while (!cancellationToken.IsCancellationRequested)
var data = await this.Receive(stream);
this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
catch (Exception exception)
private async Task Send(NetworkStream stream, byte[] buf)
await stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
await stream.WriteAsync(buf, 0, buf.Length);
private async Task<byte[]> Receive(NetworkStream stream)
var lengthBytes = new byte[4];
await stream.ReadAsync(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
var buf = new byte[length];
await stream.ReadAsync(buf, 0, buf.Length);
return buf;
Client
public class Client
private TcpClient tcpClient;
private NetworkStream stream;
public event Action<string> NewMessage;
public async void Connect(string host, int port)
try
this.tcpClient = new TcpClient();
await this.tcpClient.ConnectAsync(host, port);
this.stream = this.tcpClient.GetStream();
this.Process();
catch (Exception exception)
public void Disconnect()
try
this.stream.Close();
this.tcpClient.Close();
catch (Exception exception)
public async void SendMessage(string message)
try
await this.Send(Encoding.ASCII.GetBytes(message));
catch (Exception exception)
private async void Process()
try
while (true)
var data = await this.Receive();
this.NewMessage.SafeInvoke(Encoding.ASCII.GetString(data));
catch (Exception exception)
private async Task Send(byte[] buf)
await this.stream.WriteAsync(BitConverter.GetBytes(buf.Length), 0, 4);
await this.stream.WriteAsync(buf, 0, buf.Length);
private async Task<byte[]> Receive()
var lengthBytes = new byte[4];
await this.stream.ReadAsync(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
var buf = new byte[length];
await this.stream.ReadAsync(buf, 0, buf.Length);
return buf;

Hi,
Have you debug these two applications? Does it go into the catch exception block when you close the client or the server?
According to my test, it will throw an exception when the client or the server is closed, just log the exception message in the catch block and then you'll get it:
private async void Process()
try
while (true)
var data = await this.Receive();
this.NewMessage.Invoke(Encoding.ASCII.GetString(data));
catch (Exception exception)
Console.WriteLine(exception.Message);
Unable to read data from the transport connection: An existing   connection was forcibly closed by the remote host.
By the way, I don't know what the SafeInvoke method is, it may be an extension method, right? I used Invoke instead to test it.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey.

Similar Messages

  • When I upgraded from v4 to v5 my bookmarks was lost. I do have the one that is in the firefox toolbar. Apparently I had a bookmarks add-on. V5 changed my browser how can I determine what the program was and if the bookmarks are still there?

    When I upgraded from v4 to v5 my bookmarks was lost. I do have the one that is in the firefox toolbar. Apparently I had a bookmarks add-on. V5 changed my browser how can I determine what the program was and if the bookmarks are still there?

    Start Firefox in <u>[[Safe Mode|Safe Mode]]</u> to check if one of the extensions (Firefox/Tools > Add-ons > Extensions) or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox/Tools > Add-ons > Appearance).
    *Do NOT click the Reset button on the Safe Mode start window or otherwise make changes.
    *https://support.mozilla.org/kb/Safe+Mode
    *https://support.mozilla.org/kb/Troubleshooting+extensions+and+themes
    Websites remembering you and automatically log you in is stored in a cookie.
    *Create an allow Cookie Exception to keep such a cookie, especially for secure websites and if cookies expire when Firefox is closed.
    *Tools > Options > Privacy > Cookies: Exceptions
    In case you are using "Clear history when Firefox closes":
    *do not clear Cookies
    *do not clear Site Preferences
    *Tools > Options > Privacy > Firefox will: "Use custom settings for history": [X] "Clear history when Firefox closes" > Settings
    *https://support.mozilla.org/kb/Clear+Recent+History
    Note that clearing "Site Preferences" clears all exceptions for cookies, images, pop-up windows, software installation, and passwords.
    Clearing cookies will remove all specified (selected) cookies including cookies that have an allow exception and cookies from plugins.

  • I have an app update on my phone through the app store, but i dont have that app and when i hit update it says the item is no longer available for sale,, but i cannot get rid of the little 1 at the corner of the app store app,, how can i get rid of it

    i have an app update on my phone through the app store, but i dont have that app and when i hit update it says the item is no longer available for sale,, but i cannot get rid of the little 1 at the corner of the app store app,, how can i get rid of it,, i have iphone 5

    You installed a hacked app, originally from the Mac App Store. It contains the receipt for a different app, downloaded using an account that you don't control. You need to identify and remove the hacked app.
    Important: The app you need to remove is not necessarily the one named in the App Store notice. For example, if the App Store says you need to update "Twitter," the hacked app may be "Angry Birds" or something else entirely. Don't make any assumptions about which app you're looking for. To find it, you have to carry out a systematic search.
    Triple-click anywhere in the line of text below on this page to select it:
    kMDItemAppStoreHasReceipt=1
    Copy the selected text to the Clipboard (command-C).
    In the Finder, press the key combination command-F to open a search window, or select
    File ▹ Find
    from the menu bar. In the search window, select
    Search: This Mac
    from the row of tokens below the toolbar. Below that is a popup menu initially showing Kind. From that menu, select  Other...
    A sheet will drop down. In that sheet, select Raw Query and click OK or press return.
    Now there will be a text box to the right of popup menu. Click in that box and paste (command-V).
    The search window will show all the App Store products you've installed. Compare those search results with the list of your purchases from the App Store. To see the complete list, you may need to unhide hidden purchases. If any apps were download from the App Store using other Apple ID accounts that you control, sign in to the store under each of those ID's and check the purchases.
    At least one of the items listed in the search window is not among your purchases in the App Store. Move each such item to the Trash. You may be prompted for your administrator password. Empty the Trash.
    Log out and log back in. Test.

  • I am selling my Mac Mini. I recently purchased OS X Lion. When I restore to factory settings, how can I ensure that the operating system will still be Lion, and not the original operating system, which I believe was Snow Leopard?

    I am selling my Mac Mini. I recently purchased OS X Lion. When I restore to factory settings, how can I ensure that the operating system will still be Lion, and not the original operating system, which I believe was Snow Leopard?

    If you bought Lion from the App Store, you can't legally or practically transfer it, because it's tied to your Apple ID. Reinstall the original software from the discs that came with the machine.

  • I need to update my iPad to vision iOS 5 and up how can I do that?

    I need to update my iPad to vision iOS 5 and up how can I do that?

    You can't, that is as high as the iPad 1 can go since it only has 256MB of RAM.

  • How can I test that the ITS is setup right and working?.

    How can I test that the ITS is setup right and working?.
    At present when calling a CRM transaction (BOR object) via the Nav Bar of the Webclient IC I am getting a message box with the title of 'Message from Webpage' and the content saying 'Object expected'.
    I have re-checked the transaction launcher and navigation bar profile setting and these look okay, hence my question regarding the ITS and how we might test that its functional.
    Jason

    I assume that as I also have a call to a URL (website), which is working fine, then the ITS servicer is also working fine.
    That just leads me to know identify why my BOR object is not being called correctly.
    Within the Transaction launcher I have the following settings:
    Entries
    Launch Trans ID: ZZIC1_LT01
    Component set: ALL
    Technical details
    Description: xxxxx
    Class name: ZCL_ZZIC1_LT01
    Statefull: X
    Further Technical details
    Transaction type: BOR Transaction
    Logical system: CMDCLNT600
    BOR Object type: TSTC_UIF
    Method name: EXECUTE
    Transaction Parameters
    Parameter: Object_key
    Value: CRMD_BUS2000115
    Can anyone see any problems with these entries?.
    what's the best way to ensure that 'CRMD_BUS2000115' is a BOR object?. I can run it as a transaction.
    Jason

  • How can one accept that the only way to sync with OSX 10.9 is through I cloud?

    How can one accept that the only way to sync with OSX 10.9 is through I cloud?
    One is now obliged to send private information to an external server...

    Thank you for the link but what a waist of time.
    Who is the idiot that decided to drop manual syncing of contacts and calendars?
    I am on the point of dropping all APPLE machines!
    I am looking to sync without having to worry about security issues, keeping my files and passwords locally on my machines, and not an external server such as a cloud drive.
    Do you know if Outlook syncs also over an external server?
    Do you know of this solution? http://www.codetwo.com/public-folders/share-windows-files-securely/

  • How can I make that the cursor of a table ...

    Hello,
    how can I make that the cursor of a table (on the frontpanel) go to the starting position? I have placed a table that give back the number of the row if I doubleclick a row on the frontpanel, but when I restart the vi the cursor of the table is on this position. If I have many informations in the table and after restarting there are just one or two, I can`t see this information without scrolling to the top of the table. I want that the cursor (that I see) is at the first row. How can I make it?
    thankyou
    Schwede

    Hello,
    Sorry, I forgot to attach it in the previous post.
    Regards,
    Paulo
    Attachments:
    EditPos.vi ‏16 KB

  • How can i determine what the most recent os my imac will run?

    How can i determine what the most recent os my iMac will run?
    Serial Number QP6*****VUW
    Processor 2.16 GHz Intel Core 2 Duo
    Currently running Version 10.5.8
    <Edited by Host>

    You CAN run 10.7, but I don't advise it, buy the 10.6.3 upgrade disk from the Apple Store online and then backup files off the machine and upgrade to 10.6.3., then Software Update to 10.6.8 would be the BEST option for your older hardware and it will run most all of your 10.5 software and be faster than 10.5 or 10.7.
    If you go to 10.7 it won't run nearly any of your 10.5 software and you will have to buy all new ones for a machine that's getting a little bit dated, near it's end of life stage. 10.7 will slow your machine down, especially with low RAM.
    http://roaringapps.com/apps:table
    At your machines stage, the hard drive is getting old, the vents are clogged up with dust and it's going to cost a bit to get the drive etc upgraded. You can if you wish, but 10.7 really needs more RAM (4GB) and a faster hard drive.
    But your still subjected to the video card going out etc.
    IMO upgrade to 10.6.8 and stay there until the wheels fall off, then buy a new 10.8 machine being released after this summer or 10.9 machine.
    Harden your Mac against malware attacks

  • HT3576 how can i verify that the network or firewall is not blocking access to port 5223.

    how can i verify that the network or firewall is not blocking access to port 5223?

    Talk to someone who knows something about networking and/or firewalls on an appropriate forum.
    Configuring your network and/or firewall is beyond the scope of this forum, which is devoted to issues using the iPhone.

  • How can i ensure that the time capsule back up all my data?

    how can i ensure that the time capsule back up all my data and no any data missed during the back up? becz i was backing up my mac to time capsule for the first time and it takes only 5 hourse for 279GB which is doesnt make sense
    any idea, how to ensure that all my data been backed up

    well this tells you why you are having issues.. since you have a filevault and unless you are logged on as that user TM has no way to backup the vault.
    so that is why the backup is so small.
    And you cannot remove the file vault because the disk is too small.. you are in catch 22..
    You cannot backup and you cannot remove the vault..
    Login as the user who has the file vault and copy the files off the computer to a directory on the TC.. Then just delete the files on the computer.. that will then allow you to remove the file vault.
    But never  will I ever use file vaults so I am being theoretical .. please read it up yourself.
    http://pondini.org/TM/25.html
    You are not doing the background reading you need to understand what you are doing..
    read the whole of pondini's info.. or at least skim it so you know what is there.
    Avoid like the plague file vaults..
    When disks go belly up, as they always do.. your files will be lost. Somewhere they need to be stored in the clear.. so why bother .. put better security on the computer and forget vaults.

  • I downloaded acdsee camera flash (us$0.99) in Hong Kong's app store, but i cannot find it in the app store after i changed to another iphone. it seems that the app is no longer available in HK, how can I get back the app?

    i downloaded acdsee camera flash (us$0.99) in Hong Kong's app store, but i cannot find it in the app store after i changed to another iphone. it seems that the app is no longer available in HK, how can I get back the app?

    First make sure you are searching the name correctly.
    If the app is no longer in the App Store it is no longer available for download. This happens when Apple has found the app violates the agreement with the developer or when the developer no longer wants the app listed in the App Store.
    If the app is truly no longer in the App Store your only option is to copy it from iTunes on the computer you normall sync with.

  • How can I do that the background appears through the person who is on the pic

    how can I do that the background appears through the person who is on the pic

    Hi
    just decrease the opacity of the layer on which you have the person

  • Using an own function in a select how can i set that the function run once?

    Hi
    Using an own function in a select how can i set that the function run once, not in every row?
    Please help me
    Thanks
    Viktor

    Something like this ?
    SQL> select * from dept;
        DEPTNO DNAME                          LOC
            10 ACCOUNTING                     NEW YORK
            20 RESEARCH                       DALLAS
            30 SALES                          CHICAGO
            40 OPERATIONS                     BOSTON
    SQL> create or replace function ret_name (deptnum in number) return varchar2
      2  is
      3     name    varchar2(50);
      4  begin
      5     select dname into name
      6     from dept
      7     where deptno=deptnum;
      8     return name;
      9  exception
    10     when no_data_found then
    11             return('Not existent deptno');
    12* end;
    SQL> /
    Function created.
    SQL> select deptno, decode(rownum,1,ret_name(deptno),null) dname from dept;
        DEPTNO DNAME
            10 ACCOUNTING
            20
            30
            40
    SQL>

  • How can i indicate that the table columns have different size?

    How can i indicate that the table columns have different size?
    It is because i have a table that has several columns....but i would like to have the possibility to indicate the size for every column....could somebody help me please?
    Thanks,
    Mary

    Hi,
    don't know as much as I should about JTable, but it seems that using yourTable.getDefaultRenderer() could help you: if I clearly understood the javadoc notes, it returns an object inheriting from JLabel, so you should be able to use setHorizontalAlignment(int align) on it... no time to verify this, but I'd be thankfull if you tell me the results !!!
    Regards

Maybe you are looking for

  • Can't install iphoto 6.0.3!! help

    Hi, I hope someone can help me. I have a imac G4 256 MB w/ OX 10.4.6. I am still running iphoto 2 (what the computer came with) Now I finally want to upgrade to iphoto 6.0.3 and the computer won't let me. When I am told to select a destination to ins

  • HT1600 was told to update the tv via computer.....

    trying to update apple t.v from version to a 5.1 through the computer update. tried through it st up on tv, but no luck....anyone know how?

  • How to see the statistics in Oracle Cloud.

    While executing the select command, how can i see the execution plan and statistics in oracle cloud SQL Command Window select * from test_random where empno=1000; I need to find the consistent read and physical reads of the particular query. When I t

  • I need to bridge a printer off a wireless bridge using a 4402 WLAN Controller

    I need to bridge a printer off a wireless bridge using a 4402 WLAN Controller.  Would I need to make any changes on the 4402 WLAN Controller?

  • Save excel book

    I have a program that takes 3 different measurements 200 different times, and sends them into a book in excel.  Therefore, I would like to have it automatically save the Excel book containing the measurements after all 200 have been taken.  I am usin