How can i detected that the channel is closed with nio async?
using nio, I can wait accept, read data, write data asynchronously.
now i make a server program, and want to dected if a socket is closed by client, how can i do this?
thanks.
TO: ejp
In TCP the only way you can detect a dead connection is to attempt to write to it.
Eventually this will fail probably with a SocketException 'connection reset'.When should this happen? I don't seem to get any expection. The socket is registered for read only but it never gets read for reading again. The appropriate selection key indicates it is writable, but I don't have it registered for write operation.
Isn't there any other way to get around those dead sockets without trying to write at them? This would be quite an overhead, since server has to send some check_alive message periodically...
Similar Messages
-
How can I detect that there is an internet connection?
How can I detect that there is an internet connection?
Peter GoossensHow can I detect that there is an internet connection?
Peter Goossens
Peter,
You might want to experiment with this. It's not perfect, but...
Class
Imports System.IO
Imports System.Net
Namespace InternetConnection
Public Class SiteInfo
Private _displayName As String
Private _connectionString As String
Private Sub New(ByVal name As String, _
ByVal connectionString As String)
_displayName = name.Trim
_connectionString = connectionString.Trim
End Sub
''' <summary>
''' Gets the connection string of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
''' <summary>
''' Gets the display name of this instance.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public ReadOnly Property DisplayName() As String
Get
Return _displayName
End Get
End Property
''' <summary>
''' A method which will add a new site to your collection of SiteInfo.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for this new instance
''' of SiteInfo.</param>
''' <param name="connectionString">The connection string for this
''' new instance of SiteInfo.</param>
''' <remarks></remarks>
Public Shared Sub AddNew(ByRef siList As List(Of SiteInfo), _
ByVal displayName As String, _
ByVal connectionString As String)
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
ElseIf String.IsNullOrEmpty(connectionString) OrElse connectionString.Trim = "" Then
Throw New ArgumentException("The connection string cannot be null or empty.")
Else
If siList.Count > 0 Then
Dim findDuplicate As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "") AndAlso _
si.ConnectionString.ToLower.Replace(" "c, "") = _
connectionString.ToLower.Replace(" "c, "")
If findDuplicate.Count <> 0 Then
Throw New ArgumentException("This is a duplicate entry.")
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
Else
siList.Add(New SiteInfo(displayName, connectionString))
End If
End If
Catch ex As Exception
Throw
End Try
End Sub
''' <summary>
''' A method which will return a boolean value to indicate internet
''' connection status.
''' </summary>
''' <param name="siList">Your generic List(Of SiteInfo).</param>
''' <param name="displayName">The display name for the instance
''' of SiteInfo to use.</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function InternetIsConnected(ByVal siList As List(Of SiteInfo), _
ByVal displayName As String) As Boolean
Dim retVal As Boolean = False
Try
If siList Is Nothing Then
Throw New NullReferenceException("The collection of SiteInfo cannot be null.")
ElseIf siList.Count = 0 Then
Throw New ArgumentOutOfRangeException("Count", "The collection of SiteInfo cannot be empty.")
ElseIf String.IsNullOrEmpty(displayName) OrElse displayName.Trim = "" Then
Throw New ArgumentException("The display name cannot be null or empty.")
Else
Dim findInstance As IEnumerable(Of SiteInfo) = _
From si As SiteInfo In siList _
Where si.DisplayName.ToLower.Replace(" "c, "") = _
displayName.ToLower.Replace(" "c, "")
If findInstance.Count <> 1 Then
Throw New ArgumentException("This instance is not in the collection of SiteInfo.")
Else
retVal = TestConnection(findInstance.First.ConnectionString)
End If
End If
Catch ex As Exception
Throw
End Try
Return retVal
End Function
Private Shared Function TestConnection(ByVal url As String) As Boolean
Dim retVal As Boolean = False
Try
Dim request As WebRequest = WebRequest.Create(url)
Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
Using dataStream As Stream = response.GetResponseStream
Using reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
retVal = True
End Using
End Using
End Using
Catch ex As WebException
retVal = True
Catch ex As Exception
retVal = False
End Try
Return retVal
End Function
End Class
End Namespace
Example Usage
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
Dim siList As New List(Of InternetConnection.SiteInfo)
InternetConnection.SiteInfo.AddNew(siList, _
"Test1", _
"http://dev.virtualearth.net/REST/v1/Locations/37221?o=xml")
InternetConnection.SiteInfo.AddNew(siList, _
"Test2", _
"nothing here")
InternetConnection.SiteInfo.AddNew(siList, "Test3", _
"www.google.com")
InternetConnection.SiteInfo.AddNew(siList, "Test4", _
"http://fls-online.com")
' This will return true:
Dim bool1 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test1")
' This will return false:
Dim bool2 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test2")
' This will return false:
Dim bool3 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test3")
' This will return true:
Dim bool4 As Boolean = _
InternetConnection.SiteInfo.InternetIsConnected(siList, _
"Test4")
Stop
End Sub
End Class
Let me know your results please?
Still lost in code, just at a little higher level. -
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. -
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
SchwedeHello,
Sorry, I forgot to attach it in the previous post.
Regards,
Paulo
Attachments:
EditPos.vi 16 KB -
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.
-
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 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 -
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/ -
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
ViktorSomething 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> -
I locket laptop with find my phone program but now I forgot the password? How can I remove that password, I locket laptop with find my phone program but now I forgot the password? How can I remove that password
Repeating yourself 4 time does not make things any clearer
Read posts over on the right under the heading More Like This
Allan -
I have itune on my first computer, but i cant download it for my other one, how can i do that, i tryed many time with the link it says you download it but nothing follows thank you
I'd first try downloading an installer from the Apple website using a different web browser:
http://www.apple.com/itunes/download/
If you use Firefox instead of IE for the download (or vice versa), do you get a working installer? -
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.
JasonI 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 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 upwell 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. -
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,
MaryHi,
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 -
I will be greatful if you could answer me this question...
How can i pay on the apple store online with two credit cards, with two different billing addresses?
I know that you can use two credit cards to pay an item but the problem is that i can only put the billing address of just one of the credit cards, and since the two cards are from different people (my parents) i can't do it. They live in the same place so i don't know if i should just put one of the billing address.
Thank you.
PS. I don't know if this is the right community to ask this, sorry if i'm wrong.On the Apple Store "Payment & Pricing" page it states:
Using more than one payment card
You can also combine payment methods to pay for your purchase. Choose from the following combinations of credit cards and Apple Gift Cards:
Credit card(s) - up to two
Apple Gift Card(s) - up to eight
Apple Gift Card(s) + one credit card
During checkout, if you are paying with a gift card issued by a credit card company, you can combine it with one credit card.
Maybe you are looking for
-
Contacts Synching problem with windows address book
today i updated my itunes to ver 10, and updated my iphone os to ver 4.1, when i tried synching my contacts to windows address book, nothing happens, before today's update, i used to get a message while synching the contacts, that say eg. 25 contacts
-
Cannot "Report problem" with recent purchase.
I am using Windows 7 Pro w/ Internet Explorer 11 and iTunes v11.1.3.8. Both these are latest versions as far as I know. Despite this, when I go to report a problem with a recent download, IE shows a message I must be using the latest versions of th
-
How to set a very very long string in Binder
Hello Everybody, I want to set a string in the binder from my Filter. Is there some limit to length of string that can be set. fyi i am using the following code to do that. serviceBinder.putLocal("ListOfNames", strItemName.toString()); thanks, sapan
-
Problem on image transfer using Socket
There are a server and a client, server executes the code: ImageIO.write( bufferedImage, "jpg", outputStream ); System.out.println("writed");client executes the code: BufferedImage bufferedImage = ImageIO.read( inputStream ); System.out.println("read
-
API for loading favorites in R12
Hi all, Client would like to add a favorite on all users in R12 instance. The favorite should point to the 'Open Notifications' function. Does anyone know of a way to mass load favorite menu entries using an API or OI? It looks like the favorites end