使用C#|在套接字上发送和接收图像使用C#进行屏幕共享

时间:2018-02-22 18:44:19

标签: c# sockets

我正在尝试在C#中设置两个程序。基本上,一个简单的服务器端设置我希望客户端从服务器监听图像。然后,在接收到图像后,将其显示在PictureBox中。

**我一直遇到以下错误:

System.Drawing.dll中出现'System.ArgumentException'类型的第一次机会异常或参数无效**

服务器端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ServerComputer
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }
        Socket sendsocket;
        private void goLive_Click(object sender, EventArgs e)
        {
            try
            {
                sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //The instantiation of socket, IP for 192.168.1.106, 10001 for Port
                IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse(ipAddress.Text.Trim()), 10001);
                sendsocket.Connect(ipendpiont);
                //Establishment of end point
                Thread th = new Thread(new ThreadStart(threadimage));
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            this.Hide();    //Hidden form
        }
        private Bitmap GetScreen()
        {
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
            return bitmap;
        }
        private void threadimage()
        {
            try
            {
                while (true)
                {
                    MemoryStream ms = new MemoryStream();
                    GetScreen().Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);   //Here I use the BMP format
                    byte[] b = ms.ToArray();
                    sendsocket.Send(b);
                    Thread.Sleep(67);     //I'm here to set to send a second
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return;
            }
        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientComputer
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }
        Socket hostSocket;
        Thread thread;
        string localIP = string.Empty;
        string computrHostName = string.Empty;
        private void mainForm_Load(object sender, EventArgs e)
        {
            computrHostName = Dns.GetHostName();
            IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in hostname.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
        }
        private void liveScreen_Click(object sender, EventArgs e)
        {
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(localIP), 10001);
            //Connection node
            receiveSocket.Bind(hostIpEndPoint);
            receiveSocket.Listen(10);
            MessageBox.Show("start");
            hostSocket = receiveSocket.Accept();
            thread = new Thread(trreadimage);
            thread.Start();
            thread.IsBackground = true;
        }
        private void trreadimage()
        {
            int dataSize, i = 0;
            try
            {
                while (true)
                {
                    i++;
                    byte[] b = new byte[1024 * 1024 * 20];  //Picture of great
                    dataSize = hostSocket.Receive(b,0,b.Length,SocketFlags.None);
                    MemoryStream ms = new MemoryStream(b,0,dataSize,true);
                    //bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    Image img = Image.FromStream(ms);
                    img.Save("Image"+i+".Jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    videoBox.Image = img;
                    Console.WriteLine("Image Size: " + dataSize);
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                thread.Abort();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我无法停止重复:永远不会将原始数据发送到套接字,并期望在另一端以相同的方式接收它们。请改用协议来描述您的网络活动。在最简单的情况下,首先发送DWORD指定图像的总长度。同时,重用现有协议(如HTTP)或适合您需求的协议也是值得的。

为什么要打扰?好吧,如果你的"网络"只是一根电线,两端有两个插孔直接放入PC的网卡中,可能碰巧正常工作(仍然没有100%保修)。在实际情况下,您的网络连接"是路由器,防火墙,交换机和中间所有那些隐藏机器之间的一系列互连。他们可以(并且将会)以他们发现对他们有用的方式重新塑造你的流。所以,另一方面,你的对手如何理解:是否有收到的一切?预计会有多少个数据包?等等。

因此,如果您计划向住在附近的朋友说些什么,将一些商业数据直接发送到套接字与向窗口大喊大叫的效率相同。并且,通常我们使用具有这种通信协议的电话"嘿,彼得?...是的,它是我......听着,关注你的车,因为冰雹淋浴即将来临...再见! &#34 ;.看到区别?

答案 1 :(得分:0)

以下代码现在正在运行,我的建议很少,

尝试使用异步方法/事件通过套接字接收和发送数据,而不是使用循环或递归方法。

服务器代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerComputer
{
    publicpartialclassmainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }
        Socket sendsocket;
        privatevoid goLive_Click(object sender, EventArgs e)
        {
            try
            {
                sendsocket = newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //The instantiation of socket, IP for 192.168.1.106, 10001 for PortIPEndPoint ipendpiont = newIPEndPoint(IPAddress.Parse(ipAddress.Text.Trim()), 10001);
                sendsocket.Connect(ipendpiont);
                //Establishment of end pointThread th = newThread(newThreadStart(threadimage));
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
                return;
            }
            this.Hide();    //Hidden form
        }
        privateBitmap GetScreen()
        {
            Bitmap bitmap = newBitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
            return bitmap;
        }
        privatevoid threadimage()
        {
            try
            {
                MemoryStream ms = newMemoryStream();
                GetScreen().Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);   //Here I use the BMP formatbyte[] b = ms.ToArray();

                sendsocket.Send(b);
                ms.Close();


            }
            catch (Exception ee)
            {
                // MessageBox.Show(ee.Message);//return;
            }

            Thread.Sleep(1000);
            threadimage();
        }
    }
}

Clint Code。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ClientComputer
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }
        Socket hostSocket;
        Thread thread;
        string localIP = string.Empty;
        string computrHostName = string.Empty;
        private void mainForm_Load(object sender, EventArgs e)
        {
            computrHostName = Dns.GetHostName();
            IPHostEntry hostname = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in hostname.AddressList)
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    localIP = ip.ToString();
                }
            }
            this.Text = this.Text + " | " + localIP;

        }
        private void liveScreen_Click(object sender, EventArgs e)
        {
            connectSocket();
        }

        private void connectSocket()
        {
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint hostIpEndPoint = new IPEndPoint(IPAddress.Parse(localIP), 10001);
            //Connection node
            receiveSocket.Bind(hostIpEndPoint);
            receiveSocket.Listen(10);
            MessageBox.Show("start");
            hostSocket = receiveSocket.Accept();
            thread = new Thread(new ThreadStart(trreadimage));

            thread.IsBackground = true;
            thread.Start();
        }
        private void trreadimage()
        {
            int dataSize;
            string imageName = "Image-" + System.DateTime.Now.Ticks + ".JPG";
            try
            {

                dataSize = 0;
                byte[] b = new byte[1024 * 10000];  //Picture of great
                dataSize = hostSocket.Receive(b);
                if (dataSize > 0)
                {
                    MemoryStream ms = new MemoryStream(b);
                    Image img = Image.FromStream(ms);
                    img.Save(imageName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    videoBox.Image = img;
                    ms.Close();
                }

            }
            catch (Exception ee)
            {
                //MessageBox.Show(ee.Message);
                //thread.Abort();
            }
            System.Threading.Thread.Sleep(1500);
            trreadimage();
        }
    }
}