此篇為延續前一篇的功能,用TCP將圖面傳送/接收與呈現出來
在第一篇的時候,已經講到如何抓取桌面上的畫面,所以這篇所要做的,就是將抓下來的畫面透過TCP的方式,傳送出去與呈現,這部份會用到Thread的方式去做TCPListener.
我的做法是用Timer的方式,每隔一段時間傳送一次,所以會用到Timer這個物件,時間設太短只是加重負擔,太長,畫面斷續的會更明顯,所以這個視情況調整,也不見得要用Timer的方式,我只是用它來觸發傳圖的動作.
1: private void timer1_Tick(object sender, EventArgs e)
2: {//timer 的Tick事件
3: SendImg();
4: }
5:
6: private void SendImg()
7: {
8: try
9: {
10: TcpClient tcpc = new TcpClient(txt_IP.Text.Trim(), 5657); //txt_IP是要傳送的目的IP,看要傳到那一台電腦去,用的Port是5657
11: NetworkStream tcpStream = tcpc.GetStream();
12: byte[] SC = GetScreen(); //GetScreen就是前一篇所介紹的
13:
14: tcpStream.Write(SC, 0, SC.Length);
15: tcpStream.Flush();
16: tcpStream.Close();
17: tcpStream.Dispose();
18: tcpc.Close();
19: }
20:
21: catch (Exception ex)
22: {
23: txt_Msg.Text = ex.Message; //txt_Msg是TextBox,用來顯示錯誤訊息的.怎麼呈現,看各位想法
24: }
25: }
在傳送的部份,較為簡單,把圖給傳送出去就好,而接收部份,就較複雜一點,這部份有用到Thread的方式去運作,將接收到的圖面呈現在PictureBox上,此接收與呈現圖面的原始碼如下:
1: private Thread thImg;2: private TcpListener tcpImg;3: public bool listenerRun = true;4: //listenerRun為true,表示可以接受連接請求,false則為結束程式5: public Form1()6: {
7: InitializeComponent();
8: thImg = new Thread(new ThreadStart(ListenImg));9: thImg.Start();
10: }
11:
12: private void ListenImg()13: {
14: try15: {
16: tcpImg = new TcpListener(System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0], 5657);//在5657埠新建一個TcpListener物件17: tcpImg.Start();
18:
19: while (listenerRun)//開始監聽20: {
21: Socket s = tcpImg.AcceptSocket();
22: NetworkStream ns = new NetworkStream(s);23:
24: int size = 100000;25:
26: byte[] buff = new byte[size];27: int read = -1;28: read = ns.Read(buff, 0, size);
29:
30: if (read > 0)31: {
32: MemoryStream ms = new MemoryStream(buff, 0, size);33: this.Invoke(new SetImg(Set_Img),new object[] {Image.FromStream(ms)}); //更新圖面資訊34: this.Invoke(new SetMsg(Set_Msg), new object[] {s.RemoteEndPoint.ToString() }); //更新連線IP35: ms.Dispose();
36: this.Invoke(new SetErr(Set_Err), new object[] {""});37: }
38: }
39: }
40: catch (System.Security.SecurityException ex)41: {
42:
43: this.Invoke(new SetErr(Set_Err), new object[] { ex.Message });44:
45: }
46: catch47: {
48:
49: }
50: }
51:
52: private delegate void SetImg(Image bmp);53: private void Set_Img(Image bmp)54: {
55: pictureBox1.Image = bmp; //將圖呈現出來56: }
57:
58: private delegate void SetErr(string err);59: private void Set_Err(string err)60: {
61: txt_Msg.Text = err; //顯示錯誤訊息62: }
63:
64: private delegate void SetMsg(string msg);65: private void Set_Msg(string msg)66: {
67: txt_ImgFrom.Text = msg; //顯示畫面來自那個IP68: }
這樣子就完成了遠端桌面的抓取與傳送/呈現的功能了,但這還有很多待改善的部份,希望各位高手能提供想法,大家一起交流~
註 : 此程式所會用到的命名空間如下
using System.Threading;
using System.Net.Sockets;
using System.IO;
參考資料 :
原始碼 : 下載