Update to .net 4.6 and async try

This commit is contained in:
Afshin Arani 2020-04-01 12:56:22 +04:30
parent f24da2cbf1
commit 2d9aa26ba2
11 changed files with 116 additions and 82 deletions

View file

@ -0,0 +1,57 @@
using NetCoreServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace TLSharp.Core.Network
{
class TLClient : TcpClient
{
public delegate void ReceiveQueue(TcpMessage message);
private readonly ReceiveQueue receiveQueue;
public TLClient(IPAddress address, int port, ReceiveQueue queue) : base(address, port)
{
receiveQueue = queue;
}
protected override void OnReceived(byte[] buffer, long offset, long size)
{
var packetLengthBytes = new byte[4];
packetLengthBytes = buffer.Take(4).ToArray();
int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);
var seqBytes = new byte[4];
seqBytes = buffer.Skip(4).Take(4).ToArray();
int seq = BitConverter.ToInt32(seqBytes, 0);
int readBytes = 0;
var body = new byte[packetLength - 12];
body = buffer.Skip(8).Take(packetLength - 12).ToArray();
var crcBytes = new byte[4];
crcBytes = buffer.Skip(packetLength - 4).Take(4).ToArray();
int checksum = BitConverter.ToInt32(crcBytes, 0);
byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];
System.Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
System.Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
System.Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
var crc32 = new Ionic.Crc.CRC32();
crc32.SlurpBlock(rv, 0, rv.Length);
var validChecksum = crc32.Crc32Result;
if (checksum != validChecksum)
{
throw new InvalidOperationException("invalid checksum! skip");
}
receiveQueue(new TcpMessage(seq, body));
}
}
}

View file

@ -1,4 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
@ -10,103 +12,64 @@ namespace TLSharp.Core.Network
public class TcpTransport : IDisposable
{
private readonly TcpClient tcpClient;
private readonly NetworkStream stream;
private readonly TLClient tcpClient;
private readonly BlockingCollection<TcpMessage> ReceievedMessage = new BlockingCollection<TcpMessage>();
//private readonly NetworkStream stream;
private int sendCounter = 0;
public TcpTransport(string address, int port, TcpClientConnectionHandler handler = null)
{
if (handler == null)
{
var ipAddress = IPAddress.Parse(address);
var endpoint = new IPEndPoint(ipAddress, port);
//if (handler == null)
//{
var ipAddress = IPAddress.Parse(address);
tcpClient = new TLClient(ipAddress, port, ReceiveMessage);
tcpClient.ConnectAsync();
//}
//else
// tcpClient = handler(address, port);
}
tcpClient = new TcpClient(ipAddress.AddressFamily);
tcpClient.Connect(endpoint);
}
else
tcpClient = handler(address, port);
public void ReceiveMessage(TcpMessage message)
{
ReceievedMessage.Add(message);
//handle
if (tcpClient.Connected)
{
stream = tcpClient.GetStream();
}
}
public async Task Send(byte[] packet, CancellationToken token = default(CancellationToken))
{
if (!tcpClient.Connected)
if (!tcpClient.IsConnected)
throw new InvalidOperationException("Client not connected to server.");
var tcpMessage = new TcpMessage(sendCounter, packet);
await stream.WriteAsync(tcpMessage.Encode(), 0, tcpMessage.Encode().Length, token).ConfigureAwait(false);
tcpClient.SendAsync(tcpMessage.Encode());
sendCounter++;
}
public async Task<TcpMessage> Receive(CancellationToken token = default(CancellationToken))
{
var packetLengthBytes = new byte[4];
if (await stream.ReadAsync(packetLengthBytes, 0, 4, token).ConfigureAwait(false) != 4)
throw new InvalidOperationException("Couldn't read the packet length");
int packetLength = BitConverter.ToInt32(packetLengthBytes, 0);
var seqBytes = new byte[4];
if (await stream.ReadAsync(seqBytes, 0, 4, token).ConfigureAwait(false) != 4)
throw new InvalidOperationException("Couldn't read the sequence");
int seq = BitConverter.ToInt32(seqBytes, 0);
int readBytes = 0;
var body = new byte[packetLength - 12];
int neededToRead = packetLength - 12;
do
{
var bodyByte = new byte[packetLength - 12];
var availableBytes = await stream.ReadAsync(bodyByte, 0, neededToRead, token).ConfigureAwait(false);
neededToRead -= availableBytes;
Buffer.BlockCopy(bodyByte, 0, body, readBytes, availableBytes);
readBytes += availableBytes;
}
while (readBytes != packetLength - 12);
var crcBytes = new byte[4];
if (await stream.ReadAsync(crcBytes, 0, 4, token).ConfigureAwait(false) != 4)
throw new InvalidOperationException("Couldn't read the crc");
int checksum = BitConverter.ToInt32(crcBytes, 0);
byte[] rv = new byte[packetLengthBytes.Length + seqBytes.Length + body.Length];
Buffer.BlockCopy(packetLengthBytes, 0, rv, 0, packetLengthBytes.Length);
Buffer.BlockCopy(seqBytes, 0, rv, packetLengthBytes.Length, seqBytes.Length);
Buffer.BlockCopy(body, 0, rv, packetLengthBytes.Length + seqBytes.Length, body.Length);
var crc32 = new Ionic.Crc.CRC32();
crc32.SlurpBlock(rv, 0, rv.Length);
var validChecksum = crc32.Crc32Result;
if (checksum != validChecksum)
{
throw new InvalidOperationException("invalid checksum! skip");
}
return new TcpMessage(seq, body);
return ReceievedMessage.Take();
}
public bool IsConnected
{
get
{
return this.tcpClient.Connected;
; return this.tcpClient.IsConnected;
}
}
public void Dispose()
{
if (tcpClient.Connected)
if (tcpClient.IsConnected)
{
stream.Close();
tcpClient.Close();
//stream.Close();
tcpClient.DisconnectAsync();
tcpClient.Dispose();
}
}
}

View file

@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TLSharp.Core</RootNamespace>
<AssemblyName>TLSharp.Core</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -34,6 +35,9 @@
<HintPath>..\packages\MarkerMetro.Unity.Ionic.Zlib.2.0.0.14\lib\net35\Ionic.ZLib.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NetCoreServer, Version=1.9.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NetCoreServer.1.9.1\lib\net46\NetCoreServer.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@ -70,6 +74,7 @@
<Compile Include="Network\TcpMessage.cs" />
<Compile Include="Network\TcpTransport.cs" />
<Compile Include="Network\Exceptions\UserMigrationException.cs" />
<Compile Include="Network\TLClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Network\Requests\AckRequest.cs" />
<Compile Include="Network\Requests\PingRequest.cs" />

View file

@ -2,4 +2,5 @@
<packages>
<package id="DotNetZip" version="1.11.0" targetFramework="net451" />
<package id="MarkerMetro.Unity.Ionic.Zlib" version="2.0.0.14" targetFramework="net452" />
<package id="NetCoreServer" version="1.9.1" targetFramework="net46" />
</packages>

View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
@ -7,7 +7,8 @@
<OutputType>Library</OutputType>
<RootNamespace>TLSharp.Tests.NUnit</RootNamespace>
<AssemblyName>TLSharp.Tests.NUnit</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@ -51,4 +52,4 @@
<Name>TLSharp.Tests</Name>
</ProjectReference>
</ItemGroup>
</Project>
</Project>

View file

@ -8,7 +8,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TLSharp.Tests.VS</RootNamespace>
<AssemblyName>TLSharp.Tests.VS</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
@ -16,6 +16,7 @@
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>

View file

@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TLSharp.Tests</RootNamespace>
<AssemblyName>TLSharp.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>

View file

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
# Visual Studio Version 16
VisualStudioVersion = 16.0.29424.173
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TLSharp.Core", "TLSharp.Core\TLSharp.Core.csproj", "{400D2544-1CC6-4D8A-A62C-2292D9947A16}"
EndProject
@ -46,6 +46,12 @@ Global
{E90B705B-19FA-43BA-B952-69957976D12C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E90B705B-19FA-43BA-B952-69957976D12C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {46567A1C-7985-4A6C-AC6A-A8308DF9CE15}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
$0.TextStylePolicy = $1
@ -81,7 +87,4 @@ Global
$2.inheritsScope = text/x-csharp
$2.scope = text/x-csharp
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View file

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

View file

@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TeleSharp.Generator</RootNamespace>
<AssemblyName>TeleSharp.Generator</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>

View file

@ -9,8 +9,9 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TeleSharp.TL</RootNamespace>
<AssemblyName>TeleSharp.TL</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>