Catching of "No such host is known" exception

I have added the catching of exception if server address is invalid or
no internet connection. Also I have added the IRCClient console
application for testing.
This commit is contained in:
Andrej 2017-01-04 10:57:14 +07:00
parent 7907d22aea
commit 36b03fd4c2
8 changed files with 266 additions and 48 deletions

View File

@ -1,30 +1,46 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatSharp", "ChatSharp\ChatSharp.csproj", "{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|x86.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|x86.ActiveCfg = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ChatSharp", "ChatSharp\ChatSharp.csproj", "{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IRCClient", "IRCClient\IRCClient.csproj", "{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|Mixed Platforms = Debug|Mixed Platforms
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|Mixed Platforms = Release|Mixed Platforms
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Debug|x86.ActiveCfg = Debug|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Any CPU.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{4033AFFA-BEA3-4BDF-84EA-59A23360FD36}.Release|x86.ActiveCfg = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|Any CPU.Build.0 = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|x86.ActiveCfg = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Debug|x86.Build.0 = Debug|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|Any CPU.ActiveCfg = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|Any CPU.Build.0 = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|x86.ActiveCfg = Release|Any CPU
{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -45,6 +45,7 @@
<Compile Include="Events\ChannelTopicEventArgs.cs" />
<Compile Include="Events\ChannelEventArgs.cs" />
<Compile Include="Events\ChannelUserEventArgs.cs" />
<Compile Include="Events\ErrorEventArgs.cs" />
<Compile Include="Events\IrcNoticeEventArgs.cs" />
<Compile Include="Events\ErronousNickEventArgs.cs" />
<Compile Include="Events\ModeChangeEventArgs.cs" />

View File

@ -0,0 +1,21 @@
using System;
using System.Net.Sockets;
namespace ChatSharp.Events
{
/// <summary>
/// Raised when a Error occurs.
/// </summary>
public class ErrorEventArgs : EventArgs
{
/// <summary>
/// The error that has occured.
/// </summary>
public string Error { get; set; }
internal ErrorEventArgs(string error)
{
Error = error;
}
}
}

View File

@ -211,26 +211,36 @@ namespace ChatSharp
private void ConnectComplete(IAsyncResult result)
{
Socket.EndConnect(result);
NetworkStream = new NetworkStream(Socket);
if (UseSSL)
try
{
if (IgnoreInvalidSSL)
NetworkStream = new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true);
else
NetworkStream = new SslStream(NetworkStream);
((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname);
}
Socket.EndConnect(result);
NetworkStream = new NetworkStream(Socket);
if (UseSSL)
{
if (IgnoreInvalidSSL)
NetworkStream = new SslStream(NetworkStream, false, (sender, certificate, chain, policyErrors) => true);
else
NetworkStream = new SslStream(NetworkStream);
((SslStream)NetworkStream).AuthenticateAsClient(ServerHostname);
}
NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null);
// Write login info
if (!string.IsNullOrEmpty(User.Password))
SendRawMessage("PASS {0}", User.Password);
SendRawMessage("NICK {0}", User.Nick);
// hostname, servername are ignored by most IRC servers
SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
PingTimer.Start();
NetworkStream.BeginRead(ReadBuffer, ReadBufferIndex, ReadBuffer.Length, DataRecieved, null);
// Write login info
if (!string.IsNullOrEmpty(User.Password))
SendRawMessage("PASS {0}", User.Password);
SendRawMessage("NICK {0}", User.Nick);
// hostname, servername are ignored by most IRC servers
SendRawMessage("USER {0} hostname servername :{1}", User.User, User.RealName);
PingTimer.Start();
}
catch (SocketException e)
{
OnNetworkError(new SocketErrorEventArgs(e.SocketErrorCode));
}
catch (Exception e)
{
OnError(new Events.ErrorEventArgs(e.Message));
}
}
private void DataRecieved(IAsyncResult result)
@ -356,6 +366,14 @@ namespace ChatSharp
}
}
/// <summary>
/// Raised for errors.
/// </summary>
public event EventHandler<Events.ErrorEventArgs> Error;
internal void OnError(Events.ErrorEventArgs e)
{
if (Error != null) Error(this, e);
}
/// <summary>
/// Raised for socket errors. ChatSharp does not automatically reconnect.
/// </summary>

6
IRCClient/App.config Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>

View File

@ -0,0 +1,66 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{939CC9EC-EE9F-47DC-BC5B-D016B6B6E561}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>IRCClient</RootNamespace>
<AssemblyName>IRCClient</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ChatSharp\ChatSharp.csproj">
<Project>{4033affa-bea3-4bdf-84ea-59a23360fd36}</Project>
<Name>ChatSharp</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

54
IRCClient/Program.cs Normal file
View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ChatSharp;
namespace IRCClient
{
class Program
{
static void Main(string[] args)
{
//https://github.com/SirCmpwn/ChatSharp
var client = new IrcClient("InvalidAddress", new IrcUser("ChatSharp", "ChatSharp"));
// var client = new IrcClient("irc.freenode.net", new IrcUser("ChatSharp", "ChatSharp"));
// var client = new IrcClient("localhost", new IrcUser("ChatSharp", "ChatSharp"));
Console.WriteLine("IRC client. " + client.ServerAddress);
client.ConnectionComplete += (s, e) => {
Console.WriteLine("ConnectionComplete.");
client.JoinChannel("#botwar");
};
client.UserJoinedChannel += (s, e) => {
Console.WriteLine("The " + e.User.Nick + " user has joined to the " + e.Channel.Name + " channel.");
};
client.NetworkError += (s, e) => Console.WriteLine("NetworkError: " + new Win32Exception((int)e.SocketError).Message);
client.Error += (s, e) => Console.WriteLine("Error: " + e.Error);
client.ChannelMessageRecieved += (s, e) =>
{
var channel = client.Channels[e.PrivateMessage.Source];
if (e.PrivateMessage.Message == ".list")
channel.SendMessage(string.Join(", ", channel.Users.Select(u => u.Nick)));
else if (e.PrivateMessage.Message.StartsWith(".ban "))
{
if (!channel.UsersByMode['@'].Contains(client.User))
{
channel.SendMessage("I'm not an op here!");
return;
}
var target = e.PrivateMessage.Message.Substring(5);
client.WhoIs(target, whois => channel.ChangeMode("+b *!*@" + whois.User.Hostname));
}
};
client.ConnectAsync();
while (true) ; // Waste CPU cycles
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IRCClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IRCClient")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("939cc9ec-ee9f-47dc-bc5b-d016b6b6e561")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]