創作內容

10 GP

C# using Socket Transfer Serialization Data

作者:貓貓風 ฅ●ω●ฅ│2019-09-25 13:03:46│巴幣:20│人氣:607
.














此篇為上一篇 C# 序列化 反序列化 的延伸

直接實作使用 Ethernet 直接將資料序列化後傳出

Server端收到資料後進行反序列化將資料進行還原

最後呈現在 GUI 上


Client
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Net;  
  10. using System.Net.Sockets;  
  11. using System.Runtime.Serialization.Formatters.Binary;  
  12. using System.IO;  
  13. using data_union;  
  14. using System.Threading;  
  15.     
  16. namespace Socket_Serialize_transfer_Client  
  17. {  
  18.     public partial class Form1 : Form  
  19.     {  
  20.         public Form1()  
  21.         {  
  22.             InitializeComponent();  
  23.         }  
  24.   
  25.         BinaryFormatter _bf = new BinaryFormatter();  
  26.         MemoryStream _stream;  
  27.         data_union.data_union _data = new data_union.data_union();  
  28.         Random _rnd = new Random();  
  29.         private Thread _th;  
  30.         IPEndPoint hostEP;  
  31.         Socket socket;  
  32.         bool _start_send = false;  
  33.         bool _first = true;  
  34.         bool _fail = false;  
  35.   
  36.         private void Form1_Load(object sender, EventArgs e)  
  37.         {  
  38.             textBox3.Text = "Wait connect to Server";  
  39.               
  40.         }  
  41.   
  42.         public string CreateCheckCode()  
  43.         {  
  44.             char[] CharArray = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
  45.             'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };  
  46.             string sCode = "";  
  47.             Random random = new Random();  
  48.             for (int i = 0; i < 5; i++)  
  49.             {  
  50.                 sCode += CharArray[random.Next(CharArray.Length)];  
  51.             }  
  52.             return sCode;  
  53.         }  
  54.   
  55.         private void send_data_to_Server()  
  56.         {  
  57.             while (true)  
  58.             {  
  59.                 if (_start_send == true)  
  60.                 {  
  61.                     try  
  62.                     {  
  63.   
  64.                         byte[] bytesSend = new byte[1024];  
  65.                         //序列化  
  66.                         String rnd_str = CreateCheckCode();  
  67.                         int ran_num = _rnd.Next(0, 1024);  
  68.                         _data.data_identify = rnd_str;  
  69.                         _data.data_value = ran_num;  
  70.                         this.textBox1.Invoke((MethodInvoker)delegate  
  71.                         {  
  72.                             textBox1.Text = rnd_str;  
  73.                             textBox2.Text = ran_num.ToString();  
  74.                         });  
  75.                         _stream = new MemoryStream();  
  76.                         _bf.Serialize(_stream, _data);  
  77.   
  78.                         bytesSend = _stream.ToArray();  
  79.                         socket.SendTo(bytesSend, 0, hostEP);  
  80.   
  81.                     }  
  82.                     catch (Exception ex)  
  83.                     {  
  84.                         _fail = true;  
  85.                         _first = true;  
  86.   
  87.                         if (_th != null)  
  88.                         {  
  89.                             this.textBox3.Invoke((MethodInvoker)delegate  
  90.                             {  
  91.                                 textBox3.Text = "disconnect";  
  92.                             });  
  93.                         }  
  94.                         //MessageBox.Show(ex.ToString());  
  95.                         socket.Shutdown(SocketShutdown.Both);  
  96.                         socket.Close();  
  97.                         _th.Abort();  
  98.                         Application.Exit();  
  99.                     }  
  100.                 }  
  101.                 Thread.Sleep(1000);  
  102.             }  
  103.         }  
  104.   
  105.         private void button1_Click(object sender, EventArgs e)  
  106.         {  
  107.             if (_first)  
  108.             {  
  109.                 _first = false;  
  110.                 // 建立與Server端連線  
  111.                 hostEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse("6300"));  
  112.                 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
  113.                 ProtocolType.Tcp);  
  114.                 socket.Connect(hostEP);  
  115.                 //  
  116.                 _th = new Thread(send_data_to_Server);  
  117.                 _th.Start();  
  118.             }  
  119.             _start_send = true;  
  120.             textBox3.Text = "Connected to Server";  
  121.         }  
  122.   
  123.         private void button2_Click(object sender, EventArgs e)  
  124.         {  
  125.             _start_send = false;  
  126.         }  
  127.   
  128.         private void textBox2_KeyPress(object sender, KeyPressEventArgs e)  
  129.         {  
  130.             int keychar = (int)e.KeyChar;  
  131.             int zero = (int)'0';  
  132.             int nine = (int)'9';  
  133.             int point = (int)'.';  
  134.   
  135.             if ((keychar >= zero && keychar <= nine) || keychar == point || keychar == 8)  
  136.             {  
  137.                 e.Handled = false;  
  138.             }  
  139.             else  
  140.             {  
  141.                 e.Handled = true;  
  142.             }  
  143.         }  
  144.   
  145.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  146.         {  
  147.             if (!_fail && socket != null)  
  148.             {  
  149.                 socket.Shutdown(SocketShutdown.Both);  
  150.                 socket.Close();  
  151.                 _th.Abort();  
  152.                 _th = null;  
  153.             }  
  154.         }          
  155.     }  
  156. }  


Server
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Threading;  
  10. using System.Net.Sockets;  
  11. using System.Net;  
  12. using System.Runtime.Serialization.Formatters.Binary;  
  13. using System.IO;  
  14. using data_union;  
  15.   
  16. namespace Socket_Serialize_transfer_Server  
  17. {  
  18.     public partial class Form1 : Form  
  19.     {  
  20.         public Form1()  
  21.         {  
  22.             InitializeComponent();  
  23.         }  
  24.   
  25.         delegate void SetTextCallback(byte[] data);  
  26.         delegate void GetTextCallback();  
  27.   
  28.         Thread startThread;  
  29.         Socket socket;  
  30.         data_union.data_union _data = new data_union.data_union();  
  31.         Socket NewSocket;  
  32.         BinaryFormatter bf = new BinaryFormatter();  
  33.         MemoryStream stream;  
  34.   
  35.         private void Form1_Load(object sender, EventArgs e)  
  36.         {  
  37.             startThread = new Thread(start);  
  38.             startThread.Start();  
  39.             textBox3.Text = "Wait for Connection";  
  40.         }  
  41.   
  42.         private void start(object TransMsg)  
  43.         {  
  44.               
  45.             IPEndPoint hostEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"),
  46.             int.Parse("6300"));  
  47.             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
  48.             ProtocolType.Tcp);  
  49.             socket.Bind(hostEP);  
  50.             socket.Listen(100);  
  51.   
  52.             first:  
  53.             NewSocket = socket.Accept();  
  54.             this.textBox3.Invoke((MethodInvoker)delegate  
  55.             {  
  56.                 textBox3.Text = "Connected to Client";  
  57.             });  
  58.   
  59.             while (true)  
  60.             {  
  61.                 try  
  62.                 {  
  63.                     byte[] bytesReceive = new byte[1024];  
  64.                     int count = NewSocket.Receive(bytesReceive);  
  65.   
  66.                     //接收原始資料  
  67.                     stream = new MemoryStream(bytesReceive);  
  68.                     byte[]  byteArray = stream.ToArray();  
  69.                                           
  70.                     this.textBox4.Invoke((MethodInvoker)delegate  
  71.                     {  
  72.                         textBox4.Clear();  
  73.                         for (int i = 0; i < count; i++)  
  74.                         {  
  75.                             textBox4.Text += (char)byteArray[i];  
  76.                             if (i % 60 == 0) { textBox4.Text += "\r\n"; }  
  77.                         }  
  78.                     });  
  79.   
  80.                     //反序列化  
  81.                     data_union.data_union rev_data =
  82.                     (data_union.data_union)bf.Deserialize(stream);  
  83.                     this.textBox2.Invoke((MethodInvoker)delegate  
  84.                     {  
  85.                         this.textBox1.Text = rev_data.data_identify;  
  86.                         this.textBox2.Text = rev_data.data_value.ToString();  
  87.                     });  
  88.                 }  
  89.                 catch (Exception ex)  
  90.                 {  
  91.                     if (startThread != null)  
  92.                     {  
  93.                         this.textBox3.Invoke((MethodInvoker)delegate  
  94.                         {  
  95.                             //textBox3.Text = ex.ToString();      
  96.                             textBox3.Text = "Client Disconnect";  
  97.                         });  
  98.                     }  
  99.                     goto first;  
  100.                 }                  
  101.             }  
  102.         }  
  103.   
  104.         private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
  105.         {  
  106.             socket.Close();  
  107.             if (startThread!= null)  
  108.             {  
  109.                 startThread.Abort();  
  110.                 startThread = null;                
  111.             }    
  112.             Application.Exit();                
  113.         }  
  114.     }  
  115. }  

執行結果

Server端每秒收到Client端傳來的資料

Server端收到後將資料反序列化後呈現在畫面上

原始資料和上一篇儲存的二進為檔原始內容相同


有些亂碼部分為編碼問題,目前沒特別做處理


 
相關的網路傳輸細節可以參考以下幾篇





引用網址:https://home.gamer.com.tw/TrackBack.php?sn=4540122
All rights reserved. 版權所有,保留一切權利

相關創作

同標籤作品搜尋:涼涼風|C#

留言共 4 篇留言

真島伯爵
大大你好 最近剛開始學C# 只是網路教學的版本是好幾年前的 不知道大大有沒有教學的影片在網路上

09-25 13:10

貓貓風 ฅ●ω●ฅ
我沒拍影片也 有問題直接留言問我就可以09-25 13:16
真島伯爵
想問大大 網路使用的版本是2015年的 我下載的是今年的 兩個版本有差別嗎? Visual Studio這個

09-25 15:00

貓貓風 ฅ●ω●ฅ
基本上沒什麼差別 主要函式庫都一樣09-25 15:01
貓貓風 ฅ●ω●ฅ
不過只能向下相容 舊版不能開新版的檔案09-25 15:02
真島伯爵
好 謝謝大大

09-25 15:04

貓貓風 ฅ●ω●ฅ
是貓貓不是大大 O A O09-25 15:11
珀伽索斯(Ama)
看起來好難的樣子,
如果以前C有學好應該會比較簡顛一點[e19]

09-27 06:28

貓貓風 ฅ●ω●ฅ
[e43]09-27 08:37
我要留言提醒:您尚未登入,請先登入再留言

10喜歡★s1234567 可決定是否刪除您的留言,請勿發表違反站規文字。

前一篇:C# 序列化 反序列化... 後一篇:貓咪大戰爭 絕 黑暗天堂...

追蹤私訊切換新版閱覽

作品資料夾

ilove487奇幻小說連載中
《克蘇魯的黎明》0667.掉到海裡要先救誰?看更多我要大聲說昨天14:44


face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】