Saturday, February 20, 2010

[C#]利用Socket送傳class or struct序列化資料

一般利用Sockert都傳送文字字串.

那如果要傳送class or struct的資料怎麼辦呢.

重點就是先將class or struct序列化.

直接看範例吧.

共用Class or Struct

person.cs

01 using System;
02 using System.Collections.Generic;
03 using System.Text;
04  
05 namespace ClassLibrary2
06 {
07     [Serializable]
08     public class class_person
09     {
10         public string id;
11         public string name;
12     }
13  
14     [Serializable]
15     public struct struct_person
16     {
17         public string id;
18         public string name;
19     }
20 }

Client端,要using共用的dll

Form1.cs

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Text;
07 using System.Windows.Forms;
08 using System.Net.Sockets;
09 using System.Net;
10 using System.Threading;
11 using ClassLibrary2;
12 using System.Runtime.Serialization.Formatters.Binary;
13 using System.IO;
14  
15 namespace WindowsApplication5
16 {
17     public partial class Form1 : Form
18     {
19         public Form1()
20         {
21             InitializeComponent();
22         }
23  
24         private void btnSendClassData_Click(object sender, EventArgs e)
25         {
26             try
27             {
28                 IPEndPoint hostEP = new IPEndPoint(IPAddress.Parse(this.tbIp.Text), int.Parse(this.tbPort.Text));
29                 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
30                 socket.Connect(hostEP);
31                 byte[] bytesSend = new byte[1024];
32  
33                 //序列化
34                 BinaryFormatter bf = new BinaryFormatter();
35                 MemoryStream stream = new MemoryStream();
36                 class_person person = new class_person();
37                 person.id = this.tbId.Text;
38                 person.name = this.tbName.Text;
39                 bf.Serialize(stream, person);
40  
41                 bytesSend = stream.ToArray();
42                 socket.SendTo(bytesSend, 0, hostEP);
43                 socket.Shutdown(SocketShutdown.Both);
44                 socket.Close();
45             }
46             catch (Exception ex)
47             {
48                 MessageBox.Show(ex.ToString());
49             }
50         }
51     }
52 }


Server端,要using共用的dll

Form1.cs

001 using System;
002 using System.Collections.Generic;
003 using System.ComponentModel;
004 using System.Data;
005 using System.Drawing;
006 using System.Text;
007 using System.Windows.Forms;
008 using System.Net.Sockets;
009 using System.Net;
010 using System.Threading;
011 using ClassLibrary2;
012 using System.Runtime.Serialization.Formatters.Binary;
013 using System.IO;
014  
015 namespace WindowsApplication4
016 {
017     public partial class Form1 : Form
018     {
019         delegate void SetTextCallback(byte[] data);
020         delegate void GetTextCallback();
021  
022         Thread startThread;
023         Socket socket;
024  
025         public Form1()
026         {
027             InitializeComponent();
028         }
029  
030         private void btnOpenListen_Click(object sender, EventArgs e)
031         {
032             startThread = new Thread(new ParameterizedThreadStart(start));
033             startThread.Start();
034             this.btnOpenListen.Enabled = false;
035             this.btnCloseListen.Enabled = true;
036         }
037  
038         private void btnCloseListen_Click(object sender, EventArgs e)
039         {
040             socket.Close();
041             startThread.Abort();
042             this.btnOpenListen.Enabled = true;
043             this.btnCloseListen.Enabled = false;
044         }
045  
046         private void start(object TransMsg)
047         {
048             IPEndPoint hostEP = new IPEndPoint(IPAddress.Parse(this.tbIp.Text), int.Parse(this.tbPort.Text));
049             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
050             socket.Bind(hostEP);
051  
052             while (true)
053             {
054                 try
055                 {
056                     socket.Listen(50);
057                     Socket NewSocket = socket.Accept();
058                     byte[] bytesReceive = new byte[1024];
059                     NewSocket.Receive(bytesReceive);
060                     SetText(bytesReceive);
061                     NewSocket.Shutdown(SocketShutdown.Both);
062                     NewSocket.Close();
063                 }
064                 catch (Exception ex)
065                 {
066                     MessageBox.Show(ex.ToString());
067                 }
068             }
069         }
070  
071         private void SetText(byte[] data)
072         {
073             //反序列化
074             BinaryFormatter bf = new BinaryFormatter();
075             MemoryStream stream = new MemoryStream(data);
076             class_person person = (class_person)bf.Deserialize(stream);
077  
078             if (this.tbId.InvokeRequired)
079             {
080                 SetTextCallback d = new SetTextCallback(SetText);
081                 this.Invoke(d, new object[] { data });
082             }
083             else
084             {
085                 this.tbId.Text = person.id;
086             }
087  
088             if (this.tbName.InvokeRequired)
089             {
090                 SetTextCallback d = new SetTextCallback(SetText);
091                 this.Invoke(d, new object[] { data });
092             }
093             else
094             {
095                 this.tbName.Text = person.name;
096             }
097  
098         }
099     }
100 }


執行結果:

參考網址:

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090402141557OY6&fumcde=FUM20050124192253INM
http://topic.csdn.net/t/20031128/10/2504360.html
http://hi.baidu.com/ysdonet/blog/item/2915d2f4ebb2b56bddc47418.html

No comments:

Post a Comment