From 758c9433010da220f75fb803e4133883539d7b61 Mon Sep 17 00:00:00 2001 From: syneffort Date: Mon, 14 Nov 2022 18:20:31 +0900 Subject: [PATCH] update basic form --- SocketStudy/ClientForm/MainForm.Designer.cs | 49 +++++-- SocketStudy/ClientForm/MainForm.cs | 67 +++++++--- SocketStudy/PComm/PClient.cs | 96 ++++++++++---- SocketStudy/PComm/PClientInfo.cs | 3 +- SocketStudy/PComm/PComm.csproj | 1 + SocketStudy/PComm/PDataType.cs | 19 +++ SocketStudy/PComm/PServer.cs | 73 +++++++---- SocketStudy/PObject/PObject.csproj | 6 + SocketStudy/PUtil/PUtil.cs | 45 ++++++- SocketStudy/PUtil/PUtility.csproj | 1 + .../ChildForm/ImageForm.Designer.cs | 65 ++++++++++ SocketStudy/ServerForm/ChildForm/ImageForm.cs | 34 +++++ .../ServerForm/ChildForm/ImageForm.resx | 120 ++++++++++++++++++ SocketStudy/ServerForm/DataManager.cs | 59 +++++++++ SocketStudy/ServerForm/ServerForm.csproj | 21 ++- SocketStudy/ServerForm/mainForm.Designer.cs | 19 ++- SocketStudy/ServerForm/mainForm.cs | 84 ++++++++++-- 17 files changed, 666 insertions(+), 96 deletions(-) create mode 100644 SocketStudy/PComm/PDataType.cs create mode 100644 SocketStudy/ServerForm/ChildForm/ImageForm.Designer.cs create mode 100644 SocketStudy/ServerForm/ChildForm/ImageForm.cs create mode 100644 SocketStudy/ServerForm/ChildForm/ImageForm.resx create mode 100644 SocketStudy/ServerForm/DataManager.cs diff --git a/SocketStudy/ClientForm/MainForm.Designer.cs b/SocketStudy/ClientForm/MainForm.Designer.cs index b7c3fce..fa9102f 100644 --- a/SocketStudy/ClientForm/MainForm.Designer.cs +++ b/SocketStudy/ClientForm/MainForm.Designer.cs @@ -30,7 +30,9 @@ namespace ClientForm private void InitializeComponent() { this.logConsole = new System.Windows.Forms.TextBox(); - this.button1 = new System.Windows.Forms.Button(); + this.stringButton = new System.Windows.Forms.Button(); + this.objectButton = new System.Windows.Forms.Button(); + this.imageButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // logConsole @@ -41,25 +43,48 @@ namespace ClientForm this.logConsole.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.logConsole.Multiline = true; this.logConsole.Name = "logConsole"; + this.logConsole.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.logConsole.Size = new System.Drawing.Size(470, 344); this.logConsole.TabIndex = 1; // - // button1 + // stringButton // - 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); + this.stringButton.Location = new System.Drawing.Point(34, 39); + this.stringButton.Name = "stringButton"; + this.stringButton.Size = new System.Drawing.Size(75, 23); + this.stringButton.TabIndex = 2; + this.stringButton.Text = "string"; + this.stringButton.UseVisualStyleBackColor = true; + this.stringButton.Click += new System.EventHandler(this.stringButton_Click); + // + // objectButton + // + this.objectButton.Location = new System.Drawing.Point(146, 39); + this.objectButton.Name = "objectButton"; + this.objectButton.Size = new System.Drawing.Size(75, 23); + this.objectButton.TabIndex = 2; + this.objectButton.Text = "object"; + this.objectButton.UseVisualStyleBackColor = true; + this.objectButton.Click += new System.EventHandler(this.objectButton_Click); + // + // imageButton + // + this.imageButton.Location = new System.Drawing.Point(268, 39); + this.imageButton.Name = "imageButton"; + this.imageButton.Size = new System.Drawing.Size(75, 23); + this.imageButton.TabIndex = 2; + this.imageButton.Text = "image"; + this.imageButton.UseVisualStyleBackColor = true; + this.imageButton.Click += new System.EventHandler(this.imageButton_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.imageButton); + this.Controls.Add(this.objectButton); + this.Controls.Add(this.stringButton); this.Controls.Add(this.logConsole); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "MainForm"; @@ -72,7 +97,9 @@ namespace ClientForm #endregion private System.Windows.Forms.TextBox logConsole; - private System.Windows.Forms.Button button1; + private System.Windows.Forms.Button stringButton; + private System.Windows.Forms.Button objectButton; + private System.Windows.Forms.Button imageButton; } } diff --git a/SocketStudy/ClientForm/MainForm.cs b/SocketStudy/ClientForm/MainForm.cs index 2a86600..2817c9e 100644 --- a/SocketStudy/ClientForm/MainForm.cs +++ b/SocketStudy/ClientForm/MainForm.cs @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; @@ -20,6 +21,7 @@ namespace ClientForm private PClient client; private System.Timers.Timer heartBeatTimer; + private System.Timers.Timer testTimer; public MainForm() { @@ -29,18 +31,25 @@ namespace ClientForm private void InitInstance() { - heartBeatClient = new PClient("127.0.0.1", 7778); + string clientId = PUtil.GetRandomString(5); + string heartBeatClientId = clientId + "_hb"; + + heartBeatClient = new PClient("127.0.0.1", 7778, heartBeatClientId); heartBeatClient.OnReceived += HeartBeatClient_OnReceived; - client = new PClient("127.0.0.1", 7777); + client = new PClient("127.0.0.1", 7777, clientId); client.OnReceived += Client_OnReceived; heartBeatTimer = new System.Timers.Timer(); heartBeatTimer.Interval = 5000; heartBeatTimer.Elapsed += HeartBeatTimer_Elapsed; heartBeatTimer.Start(); - } + testTimer = new System.Timers.Timer(); + testTimer.Interval = 500; + testTimer.Elapsed += TestTimer_Elapsed; + testTimer.Start(); + } private void WriteLog(string log) { @@ -51,42 +60,68 @@ namespace ClientForm else { logConsole.AppendText($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {log}" + Environment.NewLine); - PUtil.ScrollToEnd(logConsole); + //PUtil.ScrollToEnd(logConsole); } } private void HeartBeatTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { - heartBeatClient.Send("heartbeat"); + heartBeatClient.Send(PServer.HB_CHECK); } - private void HeartBeatClient_OnReceived(PClient sender, byte[] data) + private void HeartBeatClient_OnReceived(PClient sender, PDataType dataType, byte[] data) { - string msg = Encoding.UTF8.GetString(data, 0, data.Length); - if (msg != "good") + if (dataType != PDataType.SimpleString) { - msg = "WARNING!!! BAD HEARTBEAT!!!"; + WriteLog("ERROR!!! WRONG DATA TYPE FOR HEART BEAT!!!"); + return; } - WriteLog(msg); + string msg = Encoding.UTF8.GetString(data, 0, data.Length); + if (msg != PServer.HB_CHECK) + WriteLog("WARNING!!! BAD HEARTBEAT!!!"); } - private void Client_OnReceived(PClient sender, byte[] data) + private void Client_OnReceived(PClient sender, PDataType dataType, byte[] data) { throw new NotImplementedException(); } - private void button1_Click(object sender, EventArgs e) + private void TestTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + //button1_Click(sender, e); + } + + private void stringButton_Click(object sender, EventArgs e) { + client.Send("String send test!"); + } + + private void objectButton_Click(object sender, EventArgs e) + { + Random rand = new Random(); Person person = new Person() { - Name = "Kim", - Age = 35 + Name = PUtil.GetRandomString(5), + Age = rand.Next(20, 100) }; byte[] data = PSerializer.Serialize(person); - client.Send(data); - + client.Send(PDataType.Person, data); + } + + private void imageButton_Click(object sender, EventArgs e) + { + OpenFileDialog dlg = new OpenFileDialog(); + dlg.Filter = "JPG File|*.jpg|PNG File|*.png|All File|*.*"; + if (dlg.ShowDialog() == DialogResult.Cancel) + return; + + Image img = Image.FromFile(dlg.FileName); + byte[] data = PUtil.ImageToByteArray(img); + client.Send(PDataType.Image, data); + + GC.Collect(); } } } diff --git a/SocketStudy/PComm/PClient.cs b/SocketStudy/PComm/PClient.cs index ee0a2ec..59941b5 100644 --- a/SocketStudy/PComm/PClient.cs +++ b/SocketStudy/PComm/PClient.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; @@ -13,13 +14,13 @@ namespace PComm { private readonly int BUFF_SIZE = 8192; - public delegate void ClientReceivedHandler(PClient sender, byte[] data); + public delegate void ClientReceivedHandler(PClient sender, PDataType dataType, byte[] data); public event ClientReceivedHandler OnReceived; public delegate void ClientDisconnectedHandler(PClient sender); public event ClientDisconnectedHandler Disconnected; - public string ID { get; private set; } + public string ID { get; set; } public IPEndPoint EndPoint { get; private set; } @@ -27,33 +28,49 @@ namespace PComm private Socket socket; - public PClient(string ip, int port) + public PClient(string ip, int port, string id = null) { + if (string.IsNullOrEmpty(id)) + id = Guid.NewGuid().ToString(); + socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - this.ID = Guid.NewGuid().ToString(); + this.ID = id; this.EndPoint = new IPEndPoint(IPAddress.Parse(ip), port); socket.Connect(EndPoint); + // send ID + this.Send(PDataType.ClientID, Encoding.UTF8.GetBytes(this.ID)); + socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); } public PClient(Socket accepted) { + if (string.IsNullOrEmpty(this.ID)) + this.ID = Guid.NewGuid().ToString(); + 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); + socket.Send(BitConverter.GetBytes((int)PDataType.SimpleString), 0, 4, 0); + byte[] data = Encoding.UTF8.GetBytes(msg); + byte[] length = BitConverter.GetBytes(data.Length); + socket.Send(length, 0, 4, 0); + + return socket.Send(data, SocketFlags.None); } - public int Send(byte[] msg) + public int Send(PDataType dataType, byte[] data) { - return socket.Send(msg, SocketFlags.None); + socket.Send(BitConverter.GetBytes((int)dataType), 0, 4, 0); + byte[] length = BitConverter.GetBytes(data.Length); + socket.Send(length, 0, 4, 0); + + return socket.Send(data, SocketFlags.None); } private void AcceptCallback(IAsyncResult ar) @@ -62,25 +79,58 @@ namespace PComm { socket.EndReceive(ar); - byte[] buff = new byte[BUFF_SIZE]; - - int receiveSize = socket.Receive(buff, buff.Length, SocketFlags.None); - if (receiveSize <= 0) - { - Close(); + // get data type + byte[] dataTypeBuff = new byte[4]; + socket.Receive(dataTypeBuff, dataTypeBuff.Length, SocketFlags.None); + PDataType dataType = (PDataType)BitConverter.ToInt32(dataTypeBuff, 0); - if (Disconnected != null) - Disconnected(this); - } - else if (receiveSize < buff.Length) + // get data size + byte[] sizeBuff = new byte[4]; + socket.Receive(sizeBuff, sizeBuff.Length, SocketFlags.None); + int dataSize = BitConverter.ToInt32(sizeBuff, 0); + + using (MemoryStream ms = new MemoryStream()) { - Array.Resize(ref buff, receiveSize); - } + while (dataSize > 0) + { + byte[] buff; + if (dataSize < BUFF_SIZE) + buff = new byte[dataSize]; + else + buff = new byte[BUFF_SIZE]; - if (OnReceived != null) - OnReceived(this, buff); + int receiveSize = socket.Receive(buff, buff.Length, SocketFlags.None); + + ms.Write(buff, 0, buff.Length); + dataSize -= receiveSize; + } + + byte[] data = ms.ToArray(); + + if (OnReceived != null) + OnReceived(this, dataType, data); + } socket.BeginReceive(new byte[] { 0 }, 0, 0, 0, AcceptCallback, null); + + //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) { diff --git a/SocketStudy/PComm/PClientInfo.cs b/SocketStudy/PComm/PClientInfo.cs index a03278b..5f2394f 100644 --- a/SocketStudy/PComm/PClientInfo.cs +++ b/SocketStudy/PComm/PClientInfo.cs @@ -9,7 +9,8 @@ namespace PComm public class PClientInfo { public PClient Client { get; set; } - public string LastMessage { get; set; } + public PDataType LastDataType { get; set; } + public byte[] LastData { get; set; } public DateTime CreatedAt { get; set; } public DateTime LastReceivedAt { get; set; } } diff --git a/SocketStudy/PComm/PComm.csproj b/SocketStudy/PComm/PComm.csproj index c783aab..fc1ff5b 100644 --- a/SocketStudy/PComm/PComm.csproj +++ b/SocketStudy/PComm/PComm.csproj @@ -43,6 +43,7 @@ + diff --git a/SocketStudy/PComm/PDataType.cs b/SocketStudy/PComm/PDataType.cs new file mode 100644 index 0000000..d531994 --- /dev/null +++ b/SocketStudy/PComm/PDataType.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PComm +{ + public enum PDataType + { + ClientID = 0, + + SimpleString = 10, + + Person = 100, + + Image = 200, + } +} diff --git a/SocketStudy/PComm/PServer.cs b/SocketStudy/PComm/PServer.cs index e2d1b0a..860f00f 100644 --- a/SocketStudy/PComm/PServer.cs +++ b/SocketStudy/PComm/PServer.cs @@ -10,7 +10,9 @@ namespace PComm { public class PServer { - public delegate void ClientDataReceivedHandler(PClientInfo sender, byte[] data); + public static readonly string HB_CHECK = "OK"; + + public delegate void ClientDataReceivedHandler(PClientInfo sender, PDataType dataType, byte[] data); public event ClientDataReceivedHandler OnDataReceived; private PListener listener; @@ -41,44 +43,62 @@ namespace PComm private void Listener_SocketAccepted(object sender, SocketAcceptedEventArgs e) { PClient client = new PClient(e.Accepted); - client.OnReceived += Client_Received; + client.OnReceived += Client_OnReceived; client.Disconnected += Client_Disconnected; - Debug.WriteLine($"Client accepted: {client.ID} @ { DateTime.Now}"); + Debug.WriteLine($"[{ DateTime.Now}] Temp client accepted: {client.ID}"); } - 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) + private void Client_OnReceived(PClient sender, PDataType dataType, byte[] data) { lock (garbageLock) { if (!clientInfoDict.ContainsKey(sender.ID)) clientInfoDict.Add(sender.ID, new PClientInfo()); + } - DateTime now = DateTime.Now; + DateTime now = DateTime.Now; - clientInfoDict[sender.ID].Client = sender; - clientInfoDict[sender.ID].CreatedAt = now; - clientInfoDict[sender.ID].LastReceivedAt = 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; + clientInfoDict[sender.ID].LastDataType = dataType; + clientInfoDict[sender.ID].LastData = data; + + // check client id + if (dataType == PDataType.ClientID) + { + string clientId = Encoding.UTF8.GetString(data, 0, data.Length); + clientInfoDict.Add(clientId, clientInfoDict[sender.ID]); + + lock (garbageLock) + { + if (clientInfoDict.ContainsKey(sender.ID)) + clientInfoDict.Remove(sender.ID); + } + + sender.ID = clientId; + Debug.WriteLine($"[{ DateTime.Now}] client accepted: {sender.ID}"); + + return; + } if (OnDataReceived != null && clientInfoDict.ContainsKey(sender.ID)) - OnDataReceived(clientInfoDict[sender.ID], data); + OnDataReceived(clientInfoDict[sender.ID], dataType, data); - Debug.WriteLine(($"Client message({sender.ID}): {msg} @ { DateTime.Now}")); + Debug.WriteLine(($"[{ DateTime.Now}] Client message({sender.ID}): {dataType.ToString()}({data.Length})")); + } + + private void Client_Disconnected(PClient sender) + { + if (clientInfoDict.ContainsKey(sender.ID)) + { + lock (garbageLock) + { + clientInfoDict.Remove(sender.ID); + } + } } private void GarbageTimer_Elapsed(object sender, ElapsedEventArgs e) @@ -95,5 +115,10 @@ namespace PComm clientInfoDict.Remove(key); } } + + public List ClientInfoList + { + get { return clientInfoDict.Values.ToList(); } + } } } diff --git a/SocketStudy/PObject/PObject.csproj b/SocketStudy/PObject/PObject.csproj index 9bf5474..785f76b 100644 --- a/SocketStudy/PObject/PObject.csproj +++ b/SocketStudy/PObject/PObject.csproj @@ -45,5 +45,11 @@ + + + {A88648B7-3EAE-4BFF-B5EF-2FED447C7B9C} + PComm + + \ No newline at end of file diff --git a/SocketStudy/PUtil/PUtil.cs b/SocketStudy/PUtil/PUtil.cs index 48737e7..b1ef5ac 100644 --- a/SocketStudy/PUtil/PUtil.cs +++ b/SocketStudy/PUtil/PUtil.cs @@ -1,14 +1,31 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Drawing; +using System.Drawing.Imaging; using System.Windows.Forms; namespace PUtility { public class PUtil { + private static readonly string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + public static string GetRandomString(int length = 5) + { + char[] randCharArr = new char[length]; + Random rand = new Random(); + for (int i = 0; i < length; i++) + { + randCharArr[i] = characters[rand.Next(characters.Length)]; + } + + return new string(randCharArr); + } + public static void ScrollToEnd(TextBox target) { if (target == null) @@ -17,5 +34,31 @@ namespace PUtility target.SelectionStart = target.Text.Length; target.ScrollToCaret(); } - } + + public static byte[] ImageToByteArray(Image image) + { + using (MemoryStream ms = new MemoryStream()) + { + image.Save(ms, image.RawFormat); + return ms.ToArray(); + } + } + + public static Bitmap ByteToImage(byte[] imgByteArray) + { + using (MemoryStream ms = new MemoryStream(imgByteArray)) + { + Bitmap img = Image.FromStream(ms) as Bitmap; + return img; + } + } + + public static void SaveImage(string fileName, Image img, ImageFormat format) + { + using (Image saveImage = new Bitmap(img)) + { + saveImage.Save(fileName, format); + } + } + } } diff --git a/SocketStudy/PUtil/PUtility.csproj b/SocketStudy/PUtil/PUtility.csproj index 8cb55cf..913f21b 100644 --- a/SocketStudy/PUtil/PUtility.csproj +++ b/SocketStudy/PUtil/PUtility.csproj @@ -33,6 +33,7 @@ + diff --git a/SocketStudy/ServerForm/ChildForm/ImageForm.Designer.cs b/SocketStudy/ServerForm/ChildForm/ImageForm.Designer.cs new file mode 100644 index 0000000..19bd8c5 --- /dev/null +++ b/SocketStudy/ServerForm/ChildForm/ImageForm.Designer.cs @@ -0,0 +1,65 @@ + +namespace ServerForm.ChildForm +{ + partial class ImageForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.pictureBox = new System.Windows.Forms.PictureBox(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.SuspendLayout(); + // + // pictureBox + // + this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.pictureBox.Location = new System.Drawing.Point(0, 0); + this.pictureBox.Name = "pictureBox"; + this.pictureBox.Size = new System.Drawing.Size(545, 505); + this.pictureBox.TabIndex = 0; + this.pictureBox.TabStop = false; + // + // ImageForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.BackColor = System.Drawing.Color.White; + this.ClientSize = new System.Drawing.Size(545, 505); + this.Controls.Add(this.pictureBox); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow; + this.Name = "ImageForm"; + this.Text = "Image"; + this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ImageForm_FormClosed); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private System.Windows.Forms.PictureBox pictureBox; + } +} \ No newline at end of file diff --git a/SocketStudy/ServerForm/ChildForm/ImageForm.cs b/SocketStudy/ServerForm/ChildForm/ImageForm.cs new file mode 100644 index 0000000..c1f3c3b --- /dev/null +++ b/SocketStudy/ServerForm/ChildForm/ImageForm.cs @@ -0,0 +1,34 @@ +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.ChildForm +{ + public partial class ImageForm : Form + { + private string filePath; + + public ImageForm(Image image) + { + InitializeComponent(); + InitInstance(image); + } + + private void InitInstance(Image image) + { + pictureBox.SizeMode = PictureBoxSizeMode.Zoom; + pictureBox.Image = image; + } + + private void ImageForm_FormClosed(object sender, FormClosedEventArgs e) + { + GC.Collect(); + } + } +} diff --git a/SocketStudy/ServerForm/ChildForm/ImageForm.resx b/SocketStudy/ServerForm/ChildForm/ImageForm.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SocketStudy/ServerForm/ChildForm/ImageForm.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/ServerForm/DataManager.cs b/SocketStudy/ServerForm/DataManager.cs new file mode 100644 index 0000000..9858964 --- /dev/null +++ b/SocketStudy/ServerForm/DataManager.cs @@ -0,0 +1,59 @@ +using PComm; +using PObject; +using PUtility; +using ServerForm.ChildForm; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ServerForm +{ + class DataManager + { + public static DataManager Instance { get; private set; } = new DataManager(); + + public void Process(PClientInfo clientInfo, PDataType dataType, byte[] data, LogHandler logHandler, FormHandler formHandler) + { + string log = ""; + switch (dataType) + { + case PDataType.ClientID: + log = Encoding.UTF8.GetString(data, 0, data.Length); + logHandler(clientInfo.Client, log); + break; + case PDataType.SimpleString: + log = Encoding.UTF8.GetString(data, 0, data.Length); + logHandler(clientInfo.Client, log); + break; + case PDataType.Person: + Person person = PSerializer.Deserialize(data); + log = $"Name: {person.Name}, Age: {person.Age}"; + logHandler(clientInfo.Client, log); + break; + case PDataType.Image: + Image image = PUtil.ByteToImage(data); + //string fileName = $@"{System.IO.Path.GetTempPath()}{Guid.NewGuid()}.bmp"; + //PUtil.SaveImage(fileName, image, image.RawFormat); + + log = $"Receive {data.Length.ToString("#,###")}bytes image"; + logHandler(clientInfo.Client, log); + + ImageForm imgForm = new ImageForm(image); + formHandler(imgForm); + + GC.Collect(); + break; + default: + logHandler(clientInfo.Client, "ERROR!!! UNEXPECTED DATA TYPE!!!"); + break; + } + } + } +} diff --git a/SocketStudy/ServerForm/ServerForm.csproj b/SocketStudy/ServerForm/ServerForm.csproj index 7cd1550..88d138e 100644 --- a/SocketStudy/ServerForm/ServerForm.csproj +++ b/SocketStudy/ServerForm/ServerForm.csproj @@ -46,16 +46,26 @@ - + + Form - - mainForm.cs + + ImageForm.cs + + + Form + + + MainForm.cs - - mainForm.cs + + ImageForm.cs + + + MainForm.cs ResXFileCodeGenerator @@ -93,5 +103,6 @@ PUtility + \ No newline at end of file diff --git a/SocketStudy/ServerForm/mainForm.Designer.cs b/SocketStudy/ServerForm/mainForm.Designer.cs index 3504275..7f1358c 100644 --- a/SocketStudy/ServerForm/mainForm.Designer.cs +++ b/SocketStudy/ServerForm/mainForm.Designer.cs @@ -30,24 +30,36 @@ namespace ServerForm private void InitializeComponent() { this.logConsole = new System.Windows.Forms.TextBox(); + this.clientListBox = new System.Windows.Forms.ListBox(); 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.Location = new System.Drawing.Point(251, 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.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.logConsole.Size = new System.Drawing.Size(470, 364); this.logConsole.TabIndex = 0; // + // clientListBox + // + this.clientListBox.FormattingEnabled = true; + this.clientListBox.ItemHeight = 15; + this.clientListBox.Location = new System.Drawing.Point(12, 13); + this.clientListBox.Name = "clientListBox"; + this.clientListBox.Size = new System.Drawing.Size(233, 364); + this.clientListBox.TabIndex = 2; + // // 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.ClientSize = new System.Drawing.Size(733, 390); + this.Controls.Add(this.clientListBox); 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; @@ -62,6 +74,7 @@ namespace ServerForm #endregion private System.Windows.Forms.TextBox logConsole; + private System.Windows.Forms.ListBox clientListBox; } } diff --git a/SocketStudy/ServerForm/mainForm.cs b/SocketStudy/ServerForm/mainForm.cs index 5d2a43e..1821b7f 100644 --- a/SocketStudy/ServerForm/mainForm.cs +++ b/SocketStudy/ServerForm/mainForm.cs @@ -1,6 +1,7 @@ using PComm; using PObject; using PUtility; +using ServerForm.ChildForm; using System; using System.Collections.Generic; using System.ComponentModel; @@ -13,16 +14,22 @@ using System.Windows.Forms; namespace ServerForm { + delegate void LogHandler(PClient client, string log); + delegate void FormHandler(Form form); + 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; + private LogHandler logHandler; + private FormHandler formHandler; + + private System.Timers.Timer clientCheckTimer; + public MainForm() { InitializeComponent(); @@ -37,37 +44,90 @@ namespace ServerForm heartBeatServer.OnDataReceived += HeartBeatServer_OnDataReceived; mainServer.OnDataReceived += MainServer_OnDataReceived; + logHandler = new LogHandler(WriteLog); + formHandler = new FormHandler(ShowForm); + heartBeatServer.Start(); mainServer.Start(); + + clientCheckTimer = new System.Timers.Timer(); + clientCheckTimer.Interval = 1000; + clientCheckTimer.Elapsed += ClientCheckTimer_Elapsed; + clientCheckTimer.Start(); + } + + private void WriteLog(PClient client, string log) + { + if (this.InvokeRequired) + { + this.Invoke((MethodInvoker)delegate () { WriteLog(client, log); }); + } + else + { + logConsole.AppendText($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {client.ID}: {log}" + Environment.NewLine); + //PUtil.ScrollToEnd(logConsole); + } } - private void WriteLog(string log) + private void ShowForm(Form form) { if (this.InvokeRequired) { - Invoke((MethodInvoker)delegate () { WriteLog(log); }); + this.Invoke((MethodInvoker)delegate () { ShowForm(form); }); } else { - logConsole.AppendText($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {log}" + Environment.NewLine); - PUtil.ScrollToEnd(logConsole); + form.Show(); } } - private void MainServer_OnDataReceived(PClientInfo sender, byte[] data) + private void CheckClientInfo(List clinetInfoList) { - Person person = PSerializer.Deserialize(data); + if (this.InvokeRequired) + { + this.Invoke((MethodInvoker)delegate () { CheckClientInfo(clinetInfoList); }); + } + else + { + if (clientListBox.Items != null && clientListBox.Items.Count > 1) + clientListBox.Items.Clear(); - WriteLog($"Name: {person.Name}, Age: {person.Age}"); + foreach (PClientInfo clientInfo in clinetInfoList) + { + PClient client = clientInfo.Client; + string clientView = $"{client.ID}({client.EndPoint.Address}:{client.EndPoint.Port})"; + clientListBox.Items.Add(clientView); + } + } } - private void HeartBeatServer_OnDataReceived(PClientInfo sender, byte[] data) + private void MainServer_OnDataReceived(PClientInfo sender, PDataType dataType, byte[] data) { + DataManager.Instance.Process(sender, dataType, data, logHandler, formHandler); + } + + private void HeartBeatServer_OnDataReceived(PClientInfo sender, PDataType dataType, byte[] data) + { + if (dataType != PDataType.SimpleString) + { + logHandler(sender.Client, "ERROR!!! WRONG DATA TYPE FOR HEART BEAT!!!"); + return; + } + string msg = Encoding.UTF8.GetString(data, 0, data.Length); + if (msg != PServer.HB_CHECK) + logHandler(sender.Client, "WARNING!!! BAD HEARTBEAT!!!"); - WriteLog(msg); + sender.Client.Send(PServer.HB_CHECK); + } + + private void ClientCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) + { + List clientInfoList = new List(mainServer.ClientInfoList.Count + heartBeatServer.ClientInfoList.Count); + clientInfoList.AddRange(mainServer.ClientInfoList); + clientInfoList.AddRange(heartBeatServer.ClientInfoList); - sender.Client.Send(HB_MSG); + CheckClientInfo(clientInfoList); } } }