From 300aadb23a60df7f9d0d4cf3788394e0c107ce7b Mon Sep 17 00:00:00 2001 From: syneffort Date: Fri, 11 Nov 2022 18:03:57 +0900 Subject: [PATCH] sample form (server, client) --- SocketStudy/Client/Program.cs | 42 ++++-- SocketStudy/ClientForm/App.config | 6 + SocketStudy/ClientForm/ClientForm.csproj | 97 ++++++++++++++ SocketStudy/ClientForm/MainForm.Designer.cs | 78 ++++++++++++ SocketStudy/ClientForm/MainForm.cs | 92 ++++++++++++++ SocketStudy/ClientForm/MainForm.resx | 120 ++++++++++++++++++ SocketStudy/ClientForm/Program.cs | 22 ++++ .../ClientForm/Properties/AssemblyInfo.cs | 36 ++++++ .../Properties/Resources.Designer.cs | 70 ++++++++++ .../ClientForm/Properties/Resources.resx | 117 +++++++++++++++++ .../Properties/Settings.Designer.cs | 29 +++++ .../ClientForm/Properties/Settings.settings | 7 + SocketStudy/PComm/PClient.cs | 102 +++++++++++++++ SocketStudy/PComm/PClientInfo.cs | 16 +++ SocketStudy/PComm/PComm.csproj | 52 ++++++++ SocketStudy/PComm/PListener.cs | 68 ++++++++++ SocketStudy/PComm/PServer.cs | 99 +++++++++++++++ SocketStudy/PComm/Properties/AssemblyInfo.cs | 36 ++++++ SocketStudy/PComm/SocketAcceptedEventArgs.cs | 27 ++++ SocketStudy/PObject/PObject.csproj | 49 +++++++ SocketStudy/PObject/PSerializer.cs | 51 ++++++++ SocketStudy/PObject/Person.cs | 15 +++ .../PObject/Properties/AssemblyInfo.cs | 36 ++++++ SocketStudy/PUtil/PUtil.cs | 21 +++ SocketStudy/PUtil/PUtility.csproj | 49 +++++++ SocketStudy/PUtil/Properties/AssemblyInfo.cs | 36 ++++++ SocketStudy/ServerForm/App.config | 6 + SocketStudy/ServerForm/Program.cs | 22 ++++ .../ServerForm/Properties/AssemblyInfo.cs | 36 ++++++ .../Properties/Resources.Designer.cs | 70 ++++++++++ .../ServerForm/Properties/Resources.resx | 117 +++++++++++++++++ .../Properties/Settings.Designer.cs | 29 +++++ .../ServerForm/Properties/Settings.settings | 7 + SocketStudy/ServerForm/ServerForm.csproj | 97 ++++++++++++++ SocketStudy/ServerForm/mainForm.Designer.cs | 67 ++++++++++ SocketStudy/ServerForm/mainForm.cs | 73 +++++++++++ SocketStudy/ServerForm/mainForm.resx | 120 ++++++++++++++++++ .../Server_Listener/Communication/PClient.cs | 2 +- .../Communication/PClientInfo.cs | 2 +- .../Communication/PListener.cs | 2 +- .../Server_Listener/Communication/PServer.cs | 2 +- .../Communication/SocketAcceptedEventArgs.cs | 2 +- SocketStudy/SocketStudy.sln | 30 +++++ 43 files changed, 2040 insertions(+), 17 deletions(-) create mode 100644 SocketStudy/ClientForm/App.config create mode 100644 SocketStudy/ClientForm/ClientForm.csproj create mode 100644 SocketStudy/ClientForm/MainForm.Designer.cs create mode 100644 SocketStudy/ClientForm/MainForm.cs create mode 100644 SocketStudy/ClientForm/MainForm.resx create mode 100644 SocketStudy/ClientForm/Program.cs create mode 100644 SocketStudy/ClientForm/Properties/AssemblyInfo.cs create mode 100644 SocketStudy/ClientForm/Properties/Resources.Designer.cs create mode 100644 SocketStudy/ClientForm/Properties/Resources.resx create mode 100644 SocketStudy/ClientForm/Properties/Settings.Designer.cs create mode 100644 SocketStudy/ClientForm/Properties/Settings.settings create mode 100644 SocketStudy/PComm/PClient.cs create mode 100644 SocketStudy/PComm/PClientInfo.cs create mode 100644 SocketStudy/PComm/PComm.csproj create mode 100644 SocketStudy/PComm/PListener.cs create mode 100644 SocketStudy/PComm/PServer.cs create mode 100644 SocketStudy/PComm/Properties/AssemblyInfo.cs create mode 100644 SocketStudy/PComm/SocketAcceptedEventArgs.cs create mode 100644 SocketStudy/PObject/PObject.csproj create mode 100644 SocketStudy/PObject/PSerializer.cs create mode 100644 SocketStudy/PObject/Person.cs create mode 100644 SocketStudy/PObject/Properties/AssemblyInfo.cs create mode 100644 SocketStudy/PUtil/PUtil.cs create mode 100644 SocketStudy/PUtil/PUtility.csproj create mode 100644 SocketStudy/PUtil/Properties/AssemblyInfo.cs create mode 100644 SocketStudy/ServerForm/App.config create mode 100644 SocketStudy/ServerForm/Program.cs create mode 100644 SocketStudy/ServerForm/Properties/AssemblyInfo.cs create mode 100644 SocketStudy/ServerForm/Properties/Resources.Designer.cs create mode 100644 SocketStudy/ServerForm/Properties/Resources.resx create mode 100644 SocketStudy/ServerForm/Properties/Settings.Designer.cs create mode 100644 SocketStudy/ServerForm/Properties/Settings.settings create mode 100644 SocketStudy/ServerForm/ServerForm.csproj create mode 100644 SocketStudy/ServerForm/mainForm.Designer.cs create mode 100644 SocketStudy/ServerForm/mainForm.cs create mode 100644 SocketStudy/ServerForm/mainForm.resx diff --git a/SocketStudy/Client/Program.cs b/SocketStudy/Client/Program.cs index 5a6c0f8..bc6beb0 100644 --- a/SocketStudy/Client/Program.cs +++ b/SocketStudy/Client/Program.cs @@ -13,23 +13,41 @@ namespace Client static void Main(string[] args) { - List clientList = new List(); + //List clientList = new List(); - for (int i = 0; i < CLIENT_COUNT; i++) + //for (int i = 0; i < CLIENT_COUNT; i++) + //{ + // PClientSocket clientSocket = new PClientSocket("127.0.0.1", 7777); + // clientList.Add(clientSocket); + //} + + //while (true) + //{ + // for (int i = 0; i < CLIENT_COUNT; i++) + // { + // clientList[i].Send($"Hello from client{i}"); + // } + + // Thread.Sleep(100); + //} + + int LENGTH = 10; + string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + char[] randCharArr = new char[LENGTH]; + Random rand = new Random(); + + string msg = ""; + for (int i = 0; i < LENGTH; i++) { - PClientSocket clientSocket = new PClientSocket("127.0.0.1", 7777); - clientList.Add(clientSocket); + randCharArr[i] = characters[rand.Next(characters.Length)]; } - while (true) - { - for (int i = 0; i < CLIENT_COUNT; i++) - { - clientList[i].Send($"Hello from client{i}"); - } + Console.WriteLine("Ready to send message..."); + Console.ReadKey(); - Thread.Sleep(100); - } + + PClientSocket clientSocket = new PClientSocket("127.0.0.1", 7777); + clientSocket.Send(new string(randCharArr)); Console.ReadKey(); } diff --git a/SocketStudy/ClientForm/App.config b/SocketStudy/ClientForm/App.config new file mode 100644 index 0000000..aee9adf --- /dev/null +++ b/SocketStudy/ClientForm/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/SocketStudy/ClientForm/ClientForm.csproj b/SocketStudy/ClientForm/ClientForm.csproj new file mode 100644 index 0000000..8a23807 --- /dev/null +++ b/SocketStudy/ClientForm/ClientForm.csproj @@ -0,0 +1,97 @@ + + + + + Debug + AnyCPU + {BB2DA035-8C85-41C5-87EB-157C8C776633} + WinExe + ClientForm + ClientForm + v4.8.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + + + MainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {a88648b7-3eae-4bff-b5ef-2fed447c7b9c} + PComm + + + {abe747a1-0883-42b0-9a78-1d60720288cd} + PObject + + + {b6e7f933-eb73-4d83-94fa-fb17774f1d52} + PUtility + + + + \ No newline at end of file diff --git a/SocketStudy/ClientForm/MainForm.Designer.cs b/SocketStudy/ClientForm/MainForm.Designer.cs new file mode 100644 index 0000000..b7c3fce --- /dev/null +++ b/SocketStudy/ClientForm/MainForm.Designer.cs @@ -0,0 +1,78 @@ + +namespace ClientForm +{ + partial class MainForm + { + /// + /// 필수 디자이너 변수입니다. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 사용 중인 모든 리소스를 정리합니다. + /// + /// 관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form 디자이너에서 생성한 코드 + + /// + /// 디자이너 지원에 필요한 메서드입니다. + /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요. + /// + private void InitializeComponent() + { + this.logConsole = new System.Windows.Forms.TextBox(); + this.button1 = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // logConsole + // + this.logConsole.BackColor = System.Drawing.Color.Black; + this.logConsole.ForeColor = System.Drawing.Color.SpringGreen; + this.logConsole.Location = new System.Drawing.Point(12, 93); + this.logConsole.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.logConsole.Multiline = true; + this.logConsole.Name = "logConsole"; + this.logConsole.Size = new System.Drawing.Size(470, 344); + this.logConsole.TabIndex = 1; + // + // button1 + // + this.button1.Location = new System.Drawing.Point(177, 35); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 2; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(498, 450); + this.Controls.Add(this.button1); + this.Controls.Add(this.logConsole); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Name = "MainForm"; + this.Text = "Client"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox logConsole; + private System.Windows.Forms.Button button1; + } +} + diff --git a/SocketStudy/ClientForm/MainForm.cs b/SocketStudy/ClientForm/MainForm.cs new file mode 100644 index 0000000..2a86600 --- /dev/null +++ b/SocketStudy/ClientForm/MainForm.cs @@ -0,0 +1,92 @@ +using PComm; +using PObject; +using PUtility; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ClientForm +{ + public partial class MainForm : Form + { + private PClient heartBeatClient; + private PClient client; + + private System.Timers.Timer heartBeatTimer; + + public MainForm() + { + InitializeComponent(); + InitInstance(); + } + + private void InitInstance() + { + heartBeatClient = new PClient("127.0.0.1", 7778); + heartBeatClient.OnReceived += HeartBeatClient_OnReceived; + + client = new PClient("127.0.0.1", 7777); + client.OnReceived += Client_OnReceived; + + heartBeatTimer = new System.Timers.Timer(); + heartBeatTimer.Interval = 5000; + heartBeatTimer.Elapsed += HeartBeatTimer_Elapsed; + heartBeatTimer.Start(); + } + + + private void WriteLog(string log) + { + if (this.InvokeRequired) + { + Invoke((MethodInvoker)delegate () { WriteLog(log); }); + } + else + { + logConsole.AppendText($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {log}" + Environment.NewLine); + PUtil.ScrollToEnd(logConsole); + } + } + + private void HeartBeatTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + heartBeatClient.Send("heartbeat"); + } + + private void HeartBeatClient_OnReceived(PClient sender, byte[] data) + { + string msg = Encoding.UTF8.GetString(data, 0, data.Length); + if (msg != "good") + { + msg = "WARNING!!! BAD HEARTBEAT!!!"; + } + + WriteLog(msg); + } + + private void Client_OnReceived(PClient sender, byte[] data) + { + throw new NotImplementedException(); + } + + private void button1_Click(object sender, EventArgs e) + { + Person person = new Person() + { + Name = "Kim", + Age = 35 + }; + + byte[] data = PSerializer.Serialize(person); + client.Send(data); + + } + } +} diff --git a/SocketStudy/ClientForm/MainForm.resx b/SocketStudy/ClientForm/MainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SocketStudy/ClientForm/MainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SocketStudy/ClientForm/Program.cs b/SocketStudy/ClientForm/Program.cs new file mode 100644 index 0000000..8bec380 --- /dev/null +++ b/SocketStudy/ClientForm/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ClientForm +{ + static class Program + { + /// + /// 해당 애플리케이션의 주 진입점입니다. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/SocketStudy/ClientForm/Properties/AssemblyInfo.cs b/SocketStudy/ClientForm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d8814b9 --- /dev/null +++ b/SocketStudy/ClientForm/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("ClientForm")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ClientForm")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("bb2da035-8c85-41c5-87eb-157c8c776633")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketStudy/ClientForm/Properties/Resources.Designer.cs b/SocketStudy/ClientForm/Properties/Resources.Designer.cs new file mode 100644 index 0000000..22c9f71 --- /dev/null +++ b/SocketStudy/ClientForm/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 이 코드는 도구를 사용하여 생성되었습니다. +// 런타임 버전:4.0.30319.42000 +// +// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 +// 이러한 변경 내용이 손실됩니다. +// +//------------------------------------------------------------------------------ + + +namespace ClientForm.Properties +{ + /// + /// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다. + /// + // 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder + // 클래스에서 자동으로 생성되었습니다. + // 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 + // ResGen을 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ClientForm.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대해 현재 스레드의 CurrentUICulture 속성을 + /// 재정의합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/SocketStudy/ClientForm/Properties/Resources.resx b/SocketStudy/ClientForm/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/SocketStudy/ClientForm/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SocketStudy/ClientForm/Properties/Settings.Designer.cs b/SocketStudy/ClientForm/Properties/Settings.Designer.cs new file mode 100644 index 0000000..43c130e --- /dev/null +++ b/SocketStudy/ClientForm/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace ClientForm.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/SocketStudy/ClientForm/Properties/Settings.settings b/SocketStudy/ClientForm/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/SocketStudy/ClientForm/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SocketStudy/PComm/PClient.cs b/SocketStudy/PComm/PClient.cs new file mode 100644 index 0000000..ee0a2ec --- /dev/null +++ b/SocketStudy/PComm/PClient.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace PComm +{ + public class PClient + { + private readonly int BUFF_SIZE = 8192; + + public delegate void ClientReceivedHandler(PClient sender, byte[] data); + public event ClientReceivedHandler OnReceived; + + public delegate void ClientDisconnectedHandler(PClient sender); + public event ClientDisconnectedHandler Disconnected; + + public string ID { get; private set; } + + public IPEndPoint EndPoint { get; private set; } + + public bool Connected { get { return socket.Connected; } } + + private Socket socket; + + public PClient(string ip, int port) + { + socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + this.ID = Guid.NewGuid().ToString(); + this.EndPoint = new IPEndPoint(IPAddress.Parse(ip), port); + socket.Connect(EndPoint); + + socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); + } + + public PClient(Socket accepted) + { + socket = accepted; + this.ID = Guid.NewGuid().ToString(); + this.EndPoint = (IPEndPoint)socket.RemoteEndPoint; + socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); + } + + public int Send(string msg) + { + byte[] buff = Encoding.UTF8.GetBytes(msg); + return socket.Send(buff, SocketFlags.None); + } + + public int Send(byte[] msg) + { + return socket.Send(msg, SocketFlags.None); + } + + private void AcceptCallback(IAsyncResult ar) + { + try + { + socket.EndReceive(ar); + + byte[] buff = new byte[BUFF_SIZE]; + + int receiveSize = socket.Receive(buff, buff.Length, SocketFlags.None); + if (receiveSize <= 0) + { + Close(); + + if (Disconnected != null) + Disconnected(this); + } + else if (receiveSize < buff.Length) + { + Array.Resize(ref buff, receiveSize); + } + + if (OnReceived != null) + OnReceived(this, buff); + + socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); + } + catch (Exception ex) + { + this.Close(); + + if (Disconnected != null) + Disconnected(this); + + Debug.WriteLine($"[ERROR] CleintAcceptCallback: {ex.Message}"); + } + } + + public void Close() + { + socket.Close(); + socket.Dispose(); + } + } +} diff --git a/SocketStudy/PComm/PClientInfo.cs b/SocketStudy/PComm/PClientInfo.cs new file mode 100644 index 0000000..a03278b --- /dev/null +++ b/SocketStudy/PComm/PClientInfo.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PComm +{ + public class PClientInfo + { + public PClient Client { get; set; } + public string LastMessage { get; set; } + public DateTime CreatedAt { get; set; } + public DateTime LastReceivedAt { get; set; } + } +} diff --git a/SocketStudy/PComm/PComm.csproj b/SocketStudy/PComm/PComm.csproj new file mode 100644 index 0000000..c783aab --- /dev/null +++ b/SocketStudy/PComm/PComm.csproj @@ -0,0 +1,52 @@ + + + + + Debug + AnyCPU + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C} + Library + Properties + PComm + PComm + v4.8.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SocketStudy/PComm/PListener.cs b/SocketStudy/PComm/PListener.cs new file mode 100644 index 0000000..1589a0b --- /dev/null +++ b/SocketStudy/PComm/PListener.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; +using System.Timers; + +namespace PComm +{ + delegate void SocketAcceptedHandler(object sender, SocketAcceptedEventArgs e); + + class PListener + { + public Socket BaseSocket { get; private set; } + + public bool IsRunning { get; private set; } = false; + + public int Port { get; private set; } = -1; + + public event SocketAcceptedHandler SocketAccepted; + + public PListener(int port) + { + this.Port = port; + } + + public void Start() + { + if (this.IsRunning) + return; + + this.IsRunning = true; + this.BaseSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + this.BaseSocket.Bind(new IPEndPoint(IPAddress.Any, this.Port)); + this.BaseSocket.Listen(100); + this.BaseSocket.BeginAccept(AcceptCallback, null); + } + + public void Stop() + { + if (!IsRunning) + return; + + this.IsRunning = false; + this.BaseSocket.Close(); + } + + private void AcceptCallback(IAsyncResult ar) + { + try + { + Socket socket = this.BaseSocket.EndAccept(ar); + if (SocketAccepted != null) + SocketAccepted(this, new SocketAcceptedEventArgs(socket)); + + if (IsRunning) + this.BaseSocket.BeginAccept(AcceptCallback, null); + } + catch (Exception ex) + { + Debug.WriteLine($"[ERROR] ServerAcceptCallback: {ex.Message}"); + } + } + } +} diff --git a/SocketStudy/PComm/PServer.cs b/SocketStudy/PComm/PServer.cs new file mode 100644 index 0000000..e2d1b0a --- /dev/null +++ b/SocketStudy/PComm/PServer.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Timers; + +namespace PComm +{ + public class PServer + { + public delegate void ClientDataReceivedHandler(PClientInfo sender, byte[] data); + public event ClientDataReceivedHandler OnDataReceived; + + private PListener listener; + private Dictionary clientInfoDict; + + private Timer garbageTimer; + + private object garbageLock = new object(); + + public PServer(int port) + { + listener = new PListener(port); + clientInfoDict = new Dictionary(); + + listener.SocketAccepted += Listener_SocketAccepted; + + garbageTimer = new Timer(); + garbageTimer.Interval = 10 * 1000; + garbageTimer.Elapsed += GarbageTimer_Elapsed; + } + + public void Start() + { + listener.Start(); + garbageTimer.Start(); + } + + private void Listener_SocketAccepted(object sender, SocketAcceptedEventArgs e) + { + PClient client = new PClient(e.Accepted); + client.OnReceived += Client_Received; + client.Disconnected += Client_Disconnected; + + Debug.WriteLine($"Client accepted: {client.ID} @ { DateTime.Now}"); + } + + private void Client_Disconnected(PClient sender) + { + if (clientInfoDict.ContainsKey(sender.ID)) + { + lock (garbageLock) + { + clientInfoDict.Remove(sender.ID); + } + } + } + + private void Client_Received(PClient sender, byte[] data) + { + lock (garbageLock) + { + if (!clientInfoDict.ContainsKey(sender.ID)) + clientInfoDict.Add(sender.ID, new PClientInfo()); + + DateTime now = DateTime.Now; + + clientInfoDict[sender.ID].Client = sender; + clientInfoDict[sender.ID].CreatedAt = now; + clientInfoDict[sender.ID].LastReceivedAt = now; + } + + string msg = Encoding.UTF8.GetString(data); + clientInfoDict[sender.ID].LastMessage = msg; + + if (OnDataReceived != null && clientInfoDict.ContainsKey(sender.ID)) + OnDataReceived(clientInfoDict[sender.ID], data); + + Debug.WriteLine(($"Client message({sender.ID}): {msg} @ { DateTime.Now}")); + } + + private void GarbageTimer_Elapsed(object sender, ElapsedEventArgs e) + { + List garbageKeys = new List(); + foreach (KeyValuePair item in clientInfoDict) + { + if (!item.Value.Client.Connected) + garbageKeys.Add(item.Key); + } + + foreach (string key in garbageKeys) + { + clientInfoDict.Remove(key); + } + } + } +} diff --git a/SocketStudy/PComm/Properties/AssemblyInfo.cs b/SocketStudy/PComm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..33d2622 --- /dev/null +++ b/SocketStudy/PComm/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("PComm")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PComm")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("a88648b7-3eae-4bff-b5ef-2fed447c7b9c")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketStudy/PComm/SocketAcceptedEventArgs.cs b/SocketStudy/PComm/SocketAcceptedEventArgs.cs new file mode 100644 index 0000000..04b0c6d --- /dev/null +++ b/SocketStudy/PComm/SocketAcceptedEventArgs.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace PComm +{ + class SocketAcceptedEventArgs : EventArgs + { + public Socket Accepted { get; private set; } + + public IPAddress Address { get; private set; } + + public IPEndPoint EndPoint { get; private set; } + + public SocketAcceptedEventArgs(Socket socket) + { + this.Accepted = socket; + this.EndPoint = (IPEndPoint)socket.RemoteEndPoint; + this.Address = this.EndPoint.Address; + + } + } +} diff --git a/SocketStudy/PObject/PObject.csproj b/SocketStudy/PObject/PObject.csproj new file mode 100644 index 0000000..9bf5474 --- /dev/null +++ b/SocketStudy/PObject/PObject.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {ABE747A1-0883-42B0-9A78-1D60720288CD} + Library + Properties + PObject + PObject + v4.8.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SocketStudy/PObject/PSerializer.cs b/SocketStudy/PObject/PSerializer.cs new file mode 100644 index 0000000..dc4a267 --- /dev/null +++ b/SocketStudy/PObject/PSerializer.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization.Formatters.Binary; +using System.Text; +using System.Threading.Tasks; + +namespace PObject +{ + public class PSerializer + { + public static byte[] Serialize(object obj) + { + if (obj == null) + return null; + + Type t = obj.GetType(); + if (!t.IsSerializable) + return null; + + BinaryFormatter formatter = new BinaryFormatter(); + + byte[] buff = null; + using (MemoryStream ms = new MemoryStream()) + { + formatter.Serialize(ms, obj); + buff = ms.ToArray(); + } + + return buff; + } + + public static T Deserialize(byte[] data) + { + if (data == null || data.Length < 1) + return default(T); + + T deserialized = default(T); + BinaryFormatter formatter = new BinaryFormatter(); + using (MemoryStream ms = new MemoryStream(data)) + { + object obj = formatter.Deserialize(ms); + if (obj != null && obj is T) + deserialized = (T)obj; + } + + return deserialized; + } + } +} diff --git a/SocketStudy/PObject/Person.cs b/SocketStudy/PObject/Person.cs new file mode 100644 index 0000000..8025a89 --- /dev/null +++ b/SocketStudy/PObject/Person.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PObject +{ + [Serializable] + public class Person + { + public string Name { get; set; } + public int Age { get; set; } + } +} diff --git a/SocketStudy/PObject/Properties/AssemblyInfo.cs b/SocketStudy/PObject/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ed4b012 --- /dev/null +++ b/SocketStudy/PObject/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("PObject")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PObject")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("abe747a1-0883-42b0-9a78-1d60720288cd")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketStudy/PUtil/PUtil.cs b/SocketStudy/PUtil/PUtil.cs new file mode 100644 index 0000000..48737e7 --- /dev/null +++ b/SocketStudy/PUtil/PUtil.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace PUtility +{ + public class PUtil + { + public static void ScrollToEnd(TextBox target) + { + if (target == null) + return; + + target.SelectionStart = target.Text.Length; + target.ScrollToCaret(); + } + } +} diff --git a/SocketStudy/PUtil/PUtility.csproj b/SocketStudy/PUtil/PUtility.csproj new file mode 100644 index 0000000..8cb55cf --- /dev/null +++ b/SocketStudy/PUtil/PUtility.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {B6E7F933-EB73-4D83-94FA-FB17774F1D52} + Library + Properties + PUtil + PUtil + v4.8.1 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SocketStudy/PUtil/Properties/AssemblyInfo.cs b/SocketStudy/PUtil/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1412e65 --- /dev/null +++ b/SocketStudy/PUtil/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("PUtil")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PUtil")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("b6e7f933-eb73-4d83-94fa-fb17774f1d52")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketStudy/ServerForm/App.config b/SocketStudy/ServerForm/App.config new file mode 100644 index 0000000..aee9adf --- /dev/null +++ b/SocketStudy/ServerForm/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/SocketStudy/ServerForm/Program.cs b/SocketStudy/ServerForm/Program.cs new file mode 100644 index 0000000..60f6292 --- /dev/null +++ b/SocketStudy/ServerForm/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ServerForm +{ + static class Program + { + /// + /// 해당 애플리케이션의 주 진입점입니다. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm()); + } + } +} diff --git a/SocketStudy/ServerForm/Properties/AssemblyInfo.cs b/SocketStudy/ServerForm/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..ace2ce1 --- /dev/null +++ b/SocketStudy/ServerForm/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 +// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 +// 이러한 특성 값을 변경하세요. +[assembly: AssemblyTitle("ServerForm")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ServerForm")] +[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 +// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 +// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. +[assembly: ComVisible(false)] + +// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. +[assembly: Guid("80b87bc0-61d3-410c-8fd1-9bf12493c511")] + +// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. +// +// 주 버전 +// 부 버전 +// 빌드 번호 +// 수정 버전 +// +// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 +// 기본값으로 할 수 있습니다. +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SocketStudy/ServerForm/Properties/Resources.Designer.cs b/SocketStudy/ServerForm/Properties/Resources.Designer.cs new file mode 100644 index 0000000..267fa4f --- /dev/null +++ b/SocketStudy/ServerForm/Properties/Resources.Designer.cs @@ -0,0 +1,70 @@ +//------------------------------------------------------------------------------ +// +// 이 코드는 도구를 사용하여 생성되었습니다. +// 런타임 버전:4.0.30319.42000 +// +// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 +// 이러한 변경 내용이 손실됩니다. +// +//------------------------------------------------------------------------------ + + +namespace ServerForm.Properties +{ + /// + /// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다. + /// + // 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder + // 클래스에서 자동으로 생성되었습니다. + // 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여 + // ResGen을 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ServerForm.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대해 현재 스레드의 CurrentUICulture 속성을 + /// 재정의합니다. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/SocketStudy/ServerForm/Properties/Resources.resx b/SocketStudy/ServerForm/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/SocketStudy/ServerForm/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SocketStudy/ServerForm/Properties/Settings.Designer.cs b/SocketStudy/ServerForm/Properties/Settings.Designer.cs new file mode 100644 index 0000000..9900aa2 --- /dev/null +++ b/SocketStudy/ServerForm/Properties/Settings.Designer.cs @@ -0,0 +1,29 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + + +namespace ServerForm.Properties +{ + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/SocketStudy/ServerForm/Properties/Settings.settings b/SocketStudy/ServerForm/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/SocketStudy/ServerForm/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/SocketStudy/ServerForm/ServerForm.csproj b/SocketStudy/ServerForm/ServerForm.csproj new file mode 100644 index 0000000..7cd1550 --- /dev/null +++ b/SocketStudy/ServerForm/ServerForm.csproj @@ -0,0 +1,97 @@ + + + + + Debug + AnyCPU + {80B87BC0-61D3-410C-8FD1-9BF12493C511} + WinExe + ServerForm + ServerForm + v4.8.1 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + mainForm.cs + + + + + mainForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {a88648b7-3eae-4bff-b5ef-2fed447c7b9c} + PComm + + + {abe747a1-0883-42b0-9a78-1d60720288cd} + PObject + + + {b6e7f933-eb73-4d83-94fa-fb17774f1d52} + PUtility + + + + \ No newline at end of file diff --git a/SocketStudy/ServerForm/mainForm.Designer.cs b/SocketStudy/ServerForm/mainForm.Designer.cs new file mode 100644 index 0000000..3504275 --- /dev/null +++ b/SocketStudy/ServerForm/mainForm.Designer.cs @@ -0,0 +1,67 @@ + +namespace ServerForm +{ + partial class MainForm + { + /// + /// 필수 디자이너 변수입니다. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 사용 중인 모든 리소스를 정리합니다. + /// + /// 관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form 디자이너에서 생성한 코드 + + /// + /// 디자이너 지원에 필요한 메서드입니다. + /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요. + /// + private void InitializeComponent() + { + this.logConsole = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // logConsole + // + this.logConsole.BackColor = System.Drawing.Color.Black; + this.logConsole.ForeColor = System.Drawing.Color.SpringGreen; + this.logConsole.Location = new System.Drawing.Point(12, 13); + this.logConsole.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.logConsole.Multiline = true; + this.logConsole.Name = "logConsole"; + this.logConsole.Size = new System.Drawing.Size(470, 344); + this.logConsole.TabIndex = 0; + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(493, 368); + this.Controls.Add(this.logConsole); + this.Font = new System.Drawing.Font("맑은 고딕", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129))); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); + this.Name = "MainForm"; + this.Text = "Server"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox logConsole; + } +} + diff --git a/SocketStudy/ServerForm/mainForm.cs b/SocketStudy/ServerForm/mainForm.cs new file mode 100644 index 0000000..5d2a43e --- /dev/null +++ b/SocketStudy/ServerForm/mainForm.cs @@ -0,0 +1,73 @@ +using PComm; +using PObject; +using PUtility; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ServerForm +{ + public partial class MainForm : Form + { + private readonly int PORT = 7777; + private readonly int HB_PORT = 7778; + + private readonly string HB_MSG = "good"; + + private PServer mainServer; + private PServer heartBeatServer; + + public MainForm() + { + InitializeComponent(); + InitInstance(); + } + + private void InitInstance() + { + heartBeatServer = new PServer(HB_PORT); + mainServer = new PServer(PORT); + + heartBeatServer.OnDataReceived += HeartBeatServer_OnDataReceived; + mainServer.OnDataReceived += MainServer_OnDataReceived; + + heartBeatServer.Start(); + mainServer.Start(); + } + + private void WriteLog(string log) + { + if (this.InvokeRequired) + { + Invoke((MethodInvoker)delegate () { WriteLog(log); }); + } + else + { + logConsole.AppendText($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {log}" + Environment.NewLine); + PUtil.ScrollToEnd(logConsole); + } + } + + private void MainServer_OnDataReceived(PClientInfo sender, byte[] data) + { + Person person = PSerializer.Deserialize(data); + + WriteLog($"Name: {person.Name}, Age: {person.Age}"); + } + + private void HeartBeatServer_OnDataReceived(PClientInfo sender, byte[] data) + { + string msg = Encoding.UTF8.GetString(data, 0, data.Length); + + WriteLog(msg); + + sender.Client.Send(HB_MSG); + } + } +} diff --git a/SocketStudy/ServerForm/mainForm.resx b/SocketStudy/ServerForm/mainForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SocketStudy/ServerForm/mainForm.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SocketStudy/Server_Listener/Communication/PClient.cs b/SocketStudy/Server_Listener/Communication/PClient.cs index 0e1a140..60e2cf7 100644 --- a/SocketStudy/Server_Listener/Communication/PClient.cs +++ b/SocketStudy/Server_Listener/Communication/PClient.cs @@ -9,7 +9,7 @@ using System.Threading.Tasks; namespace Server_Listener.Communication { - class PClient + internal class PClient { private readonly int BUFF_SIZE = 8192; diff --git a/SocketStudy/Server_Listener/Communication/PClientInfo.cs b/SocketStudy/Server_Listener/Communication/PClientInfo.cs index ff8ea7f..02c513e 100644 --- a/SocketStudy/Server_Listener/Communication/PClientInfo.cs +++ b/SocketStudy/Server_Listener/Communication/PClientInfo.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace Server_Listener.Communication { - class PClientInfo + internal class PClientInfo { public PClient Client { get; set; } public string LastMessage { get; set; } diff --git a/SocketStudy/Server_Listener/Communication/PListener.cs b/SocketStudy/Server_Listener/Communication/PListener.cs index 6247408..2bcbb1b 100644 --- a/SocketStudy/Server_Listener/Communication/PListener.cs +++ b/SocketStudy/Server_Listener/Communication/PListener.cs @@ -12,7 +12,7 @@ namespace Server_Listener.Communication { delegate void SocketAcceptedHandler(object sender, SocketAcceptedEventArgs e); - class PListener + internal class PListener { public Socket BaseSocket { get; private set; } diff --git a/SocketStudy/Server_Listener/Communication/PServer.cs b/SocketStudy/Server_Listener/Communication/PServer.cs index 279a668..7ed0eae 100644 --- a/SocketStudy/Server_Listener/Communication/PServer.cs +++ b/SocketStudy/Server_Listener/Communication/PServer.cs @@ -8,7 +8,7 @@ using System.Timers; namespace Server_Listener.Communication { - class PServer + internal class PServer { public delegate void ClientDataReceivedHandler(PClientInfo sender, byte[] data); public event ClientDataReceivedHandler OnDataReceived; diff --git a/SocketStudy/Server_Listener/Communication/SocketAcceptedEventArgs.cs b/SocketStudy/Server_Listener/Communication/SocketAcceptedEventArgs.cs index f7d7b3e..28243c0 100644 --- a/SocketStudy/Server_Listener/Communication/SocketAcceptedEventArgs.cs +++ b/SocketStudy/Server_Listener/Communication/SocketAcceptedEventArgs.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace Server_Listener.Communication { - class SocketAcceptedEventArgs : EventArgs + internal class SocketAcceptedEventArgs : EventArgs { public Socket Accepted { get; private set; } diff --git a/SocketStudy/SocketStudy.sln b/SocketStudy/SocketStudy.sln index 224e3d4..6c40ecc 100644 --- a/SocketStudy/SocketStudy.sln +++ b/SocketStudy/SocketStudy.sln @@ -11,6 +11,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server_Async", "Server_Asyn EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Server_Client_Listener", "Server_Listener\Server_Client_Listener.csproj", "{420F59CE-1ED7-4194-9DCA-FCB6428AFCA3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PComm", "PComm\PComm.csproj", "{A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServerForm", "ServerForm\ServerForm.csproj", "{80B87BC0-61D3-410C-8FD1-9BF12493C511}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PUtility", "PUtil\PUtility.csproj", "{B6E7F933-EB73-4D83-94FA-FB17774F1D52}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientForm", "ClientForm\ClientForm.csproj", "{BB2DA035-8C85-41C5-87EB-157C8C776633}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PObject", "PObject\PObject.csproj", "{ABE747A1-0883-42B0-9A78-1D60720288CD}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,6 +43,26 @@ Global {420F59CE-1ED7-4194-9DCA-FCB6428AFCA3}.Debug|Any CPU.Build.0 = Debug|Any CPU {420F59CE-1ED7-4194-9DCA-FCB6428AFCA3}.Release|Any CPU.ActiveCfg = Release|Any CPU {420F59CE-1ED7-4194-9DCA-FCB6428AFCA3}.Release|Any CPU.Build.0 = Release|Any CPU + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C}.Release|Any CPU.Build.0 = Release|Any CPU + {80B87BC0-61D3-410C-8FD1-9BF12493C511}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {80B87BC0-61D3-410C-8FD1-9BF12493C511}.Debug|Any CPU.Build.0 = Debug|Any CPU + {80B87BC0-61D3-410C-8FD1-9BF12493C511}.Release|Any CPU.ActiveCfg = Release|Any CPU + {80B87BC0-61D3-410C-8FD1-9BF12493C511}.Release|Any CPU.Build.0 = Release|Any CPU + {B6E7F933-EB73-4D83-94FA-FB17774F1D52}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B6E7F933-EB73-4D83-94FA-FB17774F1D52}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B6E7F933-EB73-4D83-94FA-FB17774F1D52}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B6E7F933-EB73-4D83-94FA-FB17774F1D52}.Release|Any CPU.Build.0 = Release|Any CPU + {BB2DA035-8C85-41C5-87EB-157C8C776633}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BB2DA035-8C85-41C5-87EB-157C8C776633}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BB2DA035-8C85-41C5-87EB-157C8C776633}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BB2DA035-8C85-41C5-87EB-157C8C776633}.Release|Any CPU.Build.0 = Release|Any CPU + {ABE747A1-0883-42B0-9A78-1D60720288CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABE747A1-0883-42B0-9A78-1D60720288CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ABE747A1-0883-42B0-9A78-1D60720288CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABE747A1-0883-42B0-9A78-1D60720288CD}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE