socket sample

main
syneffort 3 years ago
parent 2549944ce2
commit 37fd0b7da3
  1. 6
      SocketStudy/Client/App.config
  2. 54
      SocketStudy/Client/Client.csproj
  3. 51
      SocketStudy/Client/PClientSocket.cs
  4. 19
      SocketStudy/Client/Program.cs
  5. 36
      SocketStudy/Client/Properties/AssemblyInfo.cs
  6. 6
      SocketStudy/Server/App.config
  7. 53
      SocketStudy/Server/PServerSocket.cs
  8. 17
      SocketStudy/Server/Program.cs
  9. 36
      SocketStudy/Server/Properties/AssemblyInfo.cs
  10. 54
      SocketStudy/Server/Server_Single.csproj
  11. 6
      SocketStudy/Server_Async/App.config
  12. 62
      SocketStudy/Server_Async/PServerSocket.cs
  13. 19
      SocketStudy/Server_Async/Program.cs
  14. 36
      SocketStudy/Server_Async/Properties/AssemblyInfo.cs
  15. 54
      SocketStudy/Server_Async/Server_Async.csproj
  16. 37
      SocketStudy/SocketStudy.sln

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

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Client</RootNamespace>
<AssemblyName>Client</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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" />
<Compile Include="PClientSocket.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class PClientSocket
{
private readonly int BUFF_SIZE = 8192;
private Socket sock;
private IPEndPoint endPoint;
public PClientSocket(string ip, int port)
{
// create socket
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
}
public void Connect()
{
// connect end point
sock.Connect(endPoint);
string cmd = string.Empty;
byte[] receiveBuff = new byte[BUFF_SIZE];
Console.WriteLine("Connected... Press Q to exit.");
while ((cmd = Console.ReadLine()) != "Q")
{
byte[] buff = Encoding.UTF8.GetBytes(cmd);
// send data
sock.Send(buff, SocketFlags.None);
// receive data
int n = sock.Receive(receiveBuff);
string data = Encoding.UTF8.GetString(receiveBuff, 0, n);
Console.WriteLine($"Received: {data}");
}
sock.Close();
}
}
}

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
PClientSocket clientSocket = new PClientSocket("127.0.0.1", 7777);
clientSocket.Connect();
Console.ReadKey();
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Client")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("5263d61c-f3a5-4eda-ac6d-5f721cdbd2af")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class PServerSocket
{
private readonly int BUFF_SIZE = 8192;
private Socket sock;
private IPEndPoint endPoint;
public PServerSocket(int port)
{
// create socket
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(IPAddress.Any, port);
}
public void Listen()
{
sock.Bind(endPoint);
sock.Listen(10);
Socket clientSocket = sock.Accept();
Console.WriteLine($"Socket Accepted ({clientSocket.RemoteEndPoint.ToString()})");
Console.WriteLine("Press any key to exit.");
byte[] buff = new byte[BUFF_SIZE];
while (!Console.KeyAvailable)
{
// receive socket
int n = clientSocket.Receive(buff);
string data = Encoding.UTF8.GetString(buff, 0, n);
Console.WriteLine($"Received: {data}");
// send socket
data = "Echo from server " + data;
buff = Encoding.UTF8.GetBytes(data);
clientSocket.Send(buff, 0, buff.Length, SocketFlags.None);
}
clientSocket.Close();
sock.Close();
}
}
}

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
PServerSocket serverSocket = new PServerSocket(7777);
serverSocket.Listen();
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Server")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("408c9cc8-81eb-4ec1-b2d6-55fa2f976718")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Server</RootNamespace>
<AssemblyName>Server</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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" />
<Compile Include="PServerSocket.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

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

@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Server_Async
{
class PServerSocket
{
private readonly int BUFF_SIZE = 8192;
private Socket sock;
private IPEndPoint endPoint;
private List<Socket> clientSockets;
public PServerSocket(int port)
{
// create socket
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(IPAddress.Any, port);
}
public async Task Listen()
{
clientSockets = new List<Socket>();
sock.Bind(endPoint);
sock.Listen(100);
while (true)
{
Socket clientSocket = await Task.Factory.FromAsync(sock.BeginAccept, sock.EndAccept, null);
clientSockets.Add(clientSocket);
byte[] buff = new byte[BUFF_SIZE];
int n = await Task.Factory.FromAsync<int>(
clientSocket.BeginReceive(buff, 0, buff.Length, SocketFlags.None, null, clientSocket),
clientSocket.EndReceive);
if (n > 0)
{
string data = Encoding.UTF8.GetString(buff, 0, n);
Console.WriteLine($"Received: {data}");
data = "Echo from server " + data;
buff = Encoding.UTF8.GetBytes(data);
await Task.Factory.FromAsync(
clientSocket.BeginSend(buff, 0, buff.Length, SocketFlags.None, null, clientSocket),
clientSocket.EndSend);
}
clientSocket.Close();
}
}
}
}

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Server_Async
{
class Program
{
static void Main(string[] args)
{
PServerSocket serverSocket = new PServerSocket(7777);
serverSocket.Listen().Wait();
Console.ReadKey();
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("Server_Async")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Server_Async")]
[assembly: AssemblyCopyright("Copyright © 2022")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("94e9926e-cd35-49f8-867e-2e8b76e7fb1b")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" 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>{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>Server_Async</RootNamespace>
<AssemblyName>Server_Async</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</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" />
<Compile Include="PServerSocket.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.32630.194
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Client", "Client\Client.csproj", "{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server_Single", "Server\Server_Single.csproj", "{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server_Async", "Server_Async\Server_Async.csproj", "{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5263D61C-F3A5-4EDA-AC6D-5F721CDBD2AF}.Release|Any CPU.Build.0 = Release|Any CPU
{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}.Debug|Any CPU.Build.0 = Debug|Any CPU
{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}.Release|Any CPU.ActiveCfg = Release|Any CPU
{408C9CC8-81EB-4EC1-B2D6-55FA2F976718}.Release|Any CPU.Build.0 = Release|Any CPU
{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94E9926E-CD35-49F8-867E-2E8B76E7FB1B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2041424D-E9A7-4F3E-B634-FDCD8ED3E667}
EndGlobalSection
EndGlobal
Loading…
Cancel
Save