C# socket 服务端与客户端通信演示代码

C# socket 服务端与客户端通信演示代码,第1张

概述C# socket 服务端客户端通信演示代码

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

C# socket 服务端与客户端通信演示代码
主要实现服务端与客户端消息和文件的相互发送,服务端可以控制客户端:重启、关机、注销,截屏(截客户端的屏)。服务端也可向客户端发送闪屏。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Net;using System.Net.sockets;using System.Text;using System.windows.Forms;using System.IO;using System.Threading;using System.Runtime.InteropServices;  public delegate voID DGShowMsg(string strMsg);namespace Server{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            TextBox.CheckForIllegalCrossthreadCalls = false;//关闭跨线程修改控件检查            // txtIP.Text = Dns.GetHostEntry(Dns.GetHostname()).AddressList[0].ToString();            txtIP.Text = Dns.GetHostByname(Dns.GetHostname()).AddressList[0].ToString();        }            [Dllimport("kernel32")] ///获取系统时间        public static extern voID GetSystemTime(ref SYstemTIME_INFO stinfo);                    ///定义系统时间结构信息        [StructLayout(LayoutKind.Sequential)]        public struct SYstemTIME_INFO        {            public ushort wYear;            public ushort wMonth;            public ushort wDayOfWeek;            public ushort wDay;            public ushort wHour;            public ushort wMinute;            public ushort wSecond;            public ushort wMilliseconds;        }          Socket sokWatch = null;//负责监听 客户端段 连接请求的  套接字(女生宿舍的大妈)        Thread threaDWatch = null;//负责 调用套接字, 执行 监听请求的线程                  //开启监听 按钮        private voID btnStartListen_Click(object sender,EventArgs e)        {            //实例化 套接字 (ip4寻址协议,流式传输,TCP协议)            sokWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);                              //创建 ip对象            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());           // IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostname()).AddressList;            //string ip= this.geta            //创建网络节点对象 包含 ip和port           // IPEndPoint endpoint = new IPEndPoint(address,int.Parse(txtPort.Text.Trim())); comboBox1.Text.Trim();            IPEndPoint endpoint = new IPEndPoint(address,int.Parse(comboBox1.Text.Trim()));            //将 监听套接字  绑定到 对应的IP和端口            sokWatch.Bind(endpoint);            //设置 监听队列 长度为10(同时能够处理 10个连接请求)            sokWatch.Listen(20);            threaDWatch = new Thread(StartWatch);            threaDWatch.IsBackground = true;            threaDWatch.Start();            //txtShow.AppendText("启动服务器成功......rn");            label4.Text = "启动服务器成功......";                      }        //Dictionary<string,Socket> dictSocket = new Dictionary<string,Socket>();        Dictionary<string,ConnectionClIEnt> dictConn = new Dictionary<string,ConnectionClIEnt>();          bool isWatch = true;          #region 1.被线程调用 监听连接端口        /// <summary>        /// 被线程调用 监听连接端口        /// </summary>        voID StartWatch()        {            string recode;            while (isWatch)            {                //threaDWatch.SetApartmentState(ApartmentState.STA);                //监听 客户端 连接请求,但是,Accept会阻断当前线程                Socket sokMsg = sokWatch.Accept();//监听到请求,立即创建负责与该客户端套接字通信的套接字                ConnectionClIEnt connection = new ConnectionClIEnt(sokMsg,ShowMsg,RemoveClIEntConnection);                //将负责与当前连接请求客户端 通信的套接字所在的连接通信类 对象 装入集合                dictConn.Add(sokMsg.RemoteEndPoint.ToString(),connection);                //将 通信套接字 加入 集合,并以通信套接字的远程IpPort作为键                //dictSocket.Add(sokMsg.RemoteEndPoint.ToString(),sokMsg);                //将 通信套接字的 客户端IP端口保存在下拉框里                cboClIEnt.Items.Add(sokMsg.RemoteEndPoint.ToString());                MessageBox.Show("有一个客户端新添加!");                recode = sokMsg.RemoteEndPoint.ToString();                //调用GetSystemTime函数获取系统时间信息                SYstemTIME_INFO StInfo; StInfo = new SYstemTIME_INFO();                GetSystemTime(ref StInfo);                recode +="子计算机在"+StInfo.wYear.ToString() + "年" + StInfo.wMonth.ToString() + "月" + StInfo.wDay.ToString() + "日";                recode += (StInfo.wHour + 8).ToString() + "点" + StInfo.wMinute.ToString() + "分" + StInfo.wSecond.ToString() + "秒"+"连接服务";                                  //记录每台子计算机连接服务主机的日志                StreamWriter m_sw = new StreamWriter(System.windows.Forms.Application.StartupPath + @"\file.DAT",true);                m_sw.Writeline(recode);                m_sw.Writeline("------------------------------------------------------------------");                m_sw.Close();                //MessageBox.Show(recode);                dictConn[sokMsg.RemoteEndPoint.ToString()].SendTrue();                //启动一个新线程,负责监听该客户端发来的数据                //Thread threadConnection = new Thread(ReciveMsg);                //threadConnection.IsBackground = true;                //threadConnection.Start(sokMsg);                              }        }        #endregion          //bool isRec = true;        //与客户端通信的套接字 是否 监听消息          #region 发送消息 到指定的客户端 -btnSend_Click        //发送消息 到指定的客户端          private voID btnSend_Click(object sender,EventArgs e)        {            //byte[] arrMsg = System.Text.EnCoding.UTF8.GetBytes(txtinput.Text.Trim());            //从下拉框中 获得 要哪个客户端发送数据            string time;            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                //从字典集合中根据键获得 负责与该客户端通信的套接字,并调用send方法发送数据过去                dictConn[connectionSokKey].Send(txtinput.Text.Trim());                SYstemTIME_INFO StInfo; StInfo = new SYstemTIME_INFO();                GetSystemTime(ref StInfo);                time = StInfo.wYear.ToString() + "/" + StInfo.wMonth.ToString() + "/" + StInfo.wDay.ToString() +"  ";                time += (StInfo.wHour + 8).ToString() + ":" + StInfo.wMinute.ToString();                richTextBox1.AppendText(time + "rn");                richTextBox1.AppendText("对" + cboClIEnt.Text +"说:"+ txtinput.Text.Trim() + "rn");                txtinput.Text = "";                //sokMsg.Send(arrMsg);            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }        #endregion          //发送闪屏        private voID btnSHack_Click(object sender,EventArgs e)        {            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                dictConn[connectionSokKey].SendShake();            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }        //群闪        private voID btnSHackAll_Click(object sender,EventArgs e)        {            foreach (ConnectionClIEnt conn in dictConn.Values)            {                conn.SendShake();            }        }                 #region 2 移除与指定客户端的连接 +voID RemoveClIEntConnection(string key)        /// <summary>        /// 移除与指定客户端的连接        /// </summary>        /// <param name="key">指定客户端的IP和端口</param>        public voID RemoveClIEntConnection(string key)        {            if (dictConn.ContainsKey(key))            {                dictConn.Remove(key);                MessageBox.Show(key +"断开连接");                cboClIEnt.Items.Remove(key);            }        }        #endregion          //选择要发送的文件        private voID btnChoosefile_Click(object sender,EventArgs e)        {            OpenfileDialog ofd = new OpenfileDialog();            if (ofd.ShowDialog() == System.windows.Forms.DialogResult.OK)            {                txtfilePath.Text = ofd.filename;            }        }          //发送文件        private voID btnSendfile_Click(object sender,EventArgs e)        {            //拿到下拉框中选中的客户端IPPORT            string key = cboClIEnt.Text;            if (!string.IsNullOrEmpty(key))            {                dictConn[key].Sendfile(txtfilePath.Text.Trim());               // txtfilePath.Text = "";            }            else            {                MessageBox.Show("请选择要发送的子计算机~");            }        }          #region 向文本框显示消息 -voID ShowMsg(string msgStr)        /// <summary>        /// 向文本框显示消息        /// </summary>        /// <param name="msgStr">消息</param>        public voID ShowMsg(string msgStr)        {            //MessageBox.Show("1040414");            txtShow1.AppendText(msgStr + "rn");        }        #endregion//群消息        private voID btnSendMsgall_Click(object sender,EventArgs e)        {            string time;            foreach (ConnectionClIEnt conn in dictConn.Values)            {                conn.Send(txtinput.Text.Trim());                              }            SYstemTIME_INFO StInfo; StInfo = new SYstemTIME_INFO();            GetSystemTime(ref StInfo);            time = StInfo.wYear.ToString() + "/" + StInfo.wMonth.ToString() + "/" + StInfo.wDay.ToString()  + "  ";            time += (StInfo.wHour + 8).ToString() + ":" + StInfo.wMinute.ToString();            richTextBox1.AppendText(time + "rn");            richTextBox1.AppendText("群发消息:"+ txtinput.Text.Trim() + "rn");            txtinput.Text = "";        }//群发文件        private voID button1_Click(object sender,EventArgs e)        {              foreach (ConnectionClIEnt conn in dictConn.Values)            {               // dictConn.Sendfile(txtfilePath.Text.Trim());                conn.Sendfile(txtfilePath.Text.Trim());                                }        }          private voID button2_Click(object sender,EventArgs e)        {            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                dictConn[connectionSokKey].guanji();            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }          private voID button3_Click(object sender,EventArgs e)        {            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                dictConn[connectionSokKey].chongqi();            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }          private voID button4_Click(object sender,EventArgs e)        {            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                dictConn[connectionSokKey].zhuxiao();            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }          private voID button5_Click(object sender,EventArgs e)        {            string connectionSokKey = cboClIEnt.Text;            if (!string.IsNullOrEmpty(connectionSokKey))            {                dictConn[connectionSokKey].jIEPing();            }            else            {                MessageBox.Show("请选择要发送的子计算机~~");            }        }                 }    ///////////////////////////////////////////////////////////////////////////////////////   ////////////////////////////////////////////////////////////////////////////////////////   ////在这里,我新建了一个与客户端的通信和线程的类(ConnectionClIEnt)//////////////////////    /// <summary>    /// 与客户端的 连接通信类(包含了一个 与客户端 通信的 套接字,和线程)    /// </summary>   public class ConnectionClIEnt    {        Socket sokMsg;        DGShowMsg dgShowMsg;//负责 向主窗体文本框显示消息的方法委托        DGShowMsg dgRemoveConnection;// 负责 从主窗体 中移除 当前连接        Thread threadMsg;          #region 构造函数        /// <summary>        ///        /// </summary>        /// <param name="sokMsg">通信套接字</param>        /// <param name="dgShowMsg">向主窗体文本框显示消息的方法委托</param>        public ConnectionClIEnt(Socket sokMsg,DGShowMsg dgShowMsg,DGShowMsg dgRemoveConnection)        {            this.sokMsg = sokMsg;            this.dgShowMsg = dgShowMsg;            this.dgRemoveConnection = dgRemoveConnection;              this.threadMsg = new Thread(ReCMSg);            this.threadMsg.IsBackground = true;            this.threadMsg.Start();        }        #endregion          bool isRec = true;        #region 02负责监听客户端发送来的消息        voID ReCMSg()        {            while (isRec)            {                try                {                    byte[] arrMsg = new byte[1024 * 1024 * 1];                    //接收 对应 客户端发来的消息                    int length = sokMsg.Receive(arrMsg);                    // string abc = EnCoding.Default.GetString(arrMsg);                    // MessageBox.Show(abc);                    //将接收到的消息数组里真实消息转成字符串                                                           if (arrMsg[0] == 1)                    {                         //string abc = EnCoding.Default.GetString(arrMsg);                         //MessageBox.Show(abc);                         //发送来的是文件                         //MessageBox.Show("00000s");                         //SavefileDialog sfd = new SavefileDialog();                         SavefileDialog sfd = new SavefileDialog();                         sfd.Filter = "文本文件(.txt)|*.txt|所有文件(*.*)|*.*";                         // MessageBox.Show(sfd.Filter);                                                   //sfd.ShowDialog();                         //d出文件保存选择框                         if (sfd.ShowDialog() == System.windows.Forms.DialogResult.OK)                         {                             //MessageBox.Show("111110");                             //创建文件流                             using (fileStream fs = new fileStream(sfd.filename,fileMode.OpenorCreate))                             {                                 fs.Write(arrMsg,1,length - 1);                                 MessageBox.Show("文件保存成功!");                             }                         }                     }                    /*else if(arrMsg[0] == 2)                    {                                                  //  MemoryStream ms = new MemoryStream(arrMsg,length-1);                        MemoryStream ms = new MemoryStream(arrMsg);                        Image returnImage = Image.FromStream(ms);//??????????                        PictureBox district = (PictureBox)Application.OpenForms["Form1"].Controls["pictureBox1"].Controls["pictureBox1"];                        district.Image  =  returnImage;                       // this.savefileDialog1.filename = "";//清空名称栏                                               /*                          SavefileDialog sfd = new SavefileDialog();                        sfd.Filter = "图像文件(.jpg)|*.jpg|所有文件(*.*)|*.*";                        MessageBox.Show(sfd.Filter);                        if (DialogResult.OK == sfd.ShowDialog())                        {                            string strfilename = sfd.filename;                            //Image img = (Image)this.pictureBox1.Image;                            returnImage.Save(strfilename);                        }                                             }*/                     else//发送来的是消息                     {                        //MessageBox.Show("2222");                        string strMsg = sokMsg.RemoteEndPoint.ToString()+"说:"+"rn"+System.Text.EnCoding.UTF8.GetString(arrMsg,length); //// 我在这里  Request.ServerVariables.Get("Remote_Addr").ToString()+                        //通过委托 显示消息到 窗体的文本框                        dgShowMsg(strMsg);                      }                                                                                            //MessageBox.Show("11111");              }              catch (Exception ex)               {                  isRec = false;                 //从主窗体中 移除 下拉框中对应的客户端选择项,同时 移除 集合中对应的 ConnectionClIEnt对象                    dgRemoveConnection(sokMsg.RemoteEndPoint.ToString());                }            }        }        #endregion          #region 03向客户端发送消息        /// <summary>        /// 向客户端发送消息        /// </summary>        /// <param name="strMsg"></param>        public voID Send(string strMsg)        {            byte[] arrMsg = System.Text.EnCoding.UTF8.GetBytes(strMsg);            byte[] arrMsgFinal = new byte[arrMsg.Length + 1];              arrMsgFinal[0] = 0;//设置 数据标识位等于0,代表 发送的是 文字            arrMsg.copyTo(arrMsgFinal,1);              sokMsg.Send(arrMsgFinal);        }        #endregion          #region 04向客户端发送文件数据 +voID Sendfile(string strPath)        /// <summary>        /// 04向客户端发送文件数据        /// </summary>        /// <param name="strPath">文件路径</param>        public voID Sendfile(string strPath)        {            //通过文件流 读取文件内容            //MessageBox.Show("12540");            using (fileStream fs = new fileStream(strPath,fileMode.OpenorCreate))            {                byte[] arrfile = new byte[1024 * 1024 * 2];                //读取文件内容到字节数组,并 获得 实际文件大小                int length = fs.Read(arrfile,arrfile.Length);                //定义一个 新数组,长度为文件实际长度 +1                byte[] arrfileFina = new byte[length + 1];                arrfileFina[0] = 1;//设置 数据标识位等于1,代表 发送的是文件                //将 文件数据数组 复制到 新数组中,下标从1开始                //arrfile.copyTo(arrfileFina,1);                Buffer.Blockcopy(arrfile,arrfileFina,length);               // MessageBox.Show("120");                //发送文件数据                sokMsg.Send(arrfileFina);//,length + 1,SocketFlags.None);            }        }        #endregion          #region 05向客户端发送闪屏        /// <summary>        /// 向客户端发送闪屏        /// </summary>        /// <param name="strMsg"></param>        public voID SendShake()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 2;            sokMsg.Send(arrMsgFinal);        }        #endregion          #region 06关闭与客户端连接        /// <summary>        /// 关闭与客户端连接        /// </summary>        public voID CloseConnection()        {            isRec = false;        }        #endregion          #region 07向客户端发送连接成功提示        /// <summary>        /// 向客户端发送连接成功提示        /// </summary>        /// <param name="strMsg"></param>        public voID SendTrue()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 3;            sokMsg.Send(arrMsgFinal);        }        #endregion          #region 08向客户端发送关机命令        /// <summary>        /// 向客户端发送关机命令        /// </summary>        /// <param name="strMsg"></param>        public voID guanji()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 4;            sokMsg.Send(arrMsgFinal);        }        #endregion          #region 09向客户端发送重启命令        /// <summary>        /// 向客户端发送关机命令        /// </summary>        /// <param name="strMsg"></param>        public voID chongqi()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 5;            sokMsg.Send(arrMsgFinal);        }        #endregion          #region 10向客户端发送待机命令        /// <summary>        /// 向客户端发送关机命令        /// </summary>        /// <param name="strMsg"></param>        public voID zhuxiao()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 6;            sokMsg.Send(arrMsgFinal);        }       #endregion          #region 11向客户端发送截屏命令        /// <summary>        /// 向客户端发送截屏命令        /// </summary>        /// <param name="strMsg"></param>        public voID jIEPing()        {            byte[] arrMsgFinal = new byte[1];            arrMsgFinal[0] = 7;            sokMsg.Send(arrMsgFinal);        }        #endregion    }  }

客户端:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Net.sockets;using System.Net;using System.Threading;using System.windows.Forms;using System.IO;using System.Text;using System.Runtime.InteropServices;    public delegate voID DGShowMsg(string strMsg);namespace ClIEnt{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            TextBox.CheckForIllegalCrossthreadCalls = false;                      }        #region[成员函数]        ///<summary>        ///图像函数        ///</summary>        private Image _img;        #endregion        [StructLayout(LayoutKind.Sequential,Pack = 1)]          internal struct TokPriv1LuID        {              public int Count;              public long LuID;              public int Attr;          }          [Dllimport("kernel32.dll",ExactSpelling = true)]          internal static extern IntPtr GetCurrentProcess();          [Dllimport("advAPI32.dll",ExactSpelling = true,SetLastError = true)]          internal static extern bool OpenProcesstoken(IntPtr h,int acc,ref IntPtr phtok);          [Dllimport("advAPI32.dll",SetLastError = true)]          internal static extern bool LookupPrivilegeValue(string host,string name,ref long pluID);          [Dllimport("advAPI32.dll",SetLastError = true)]          internal static extern bool AdjustTokenPrivileges(IntPtr htok,bool disall,ref TokPriv1LuID newst,int len,IntPtr prev,IntPtr relen);          [Dllimport("user32.dll",SetLastError = true)]          internal static extern bool ExitwindowsEx(int flg,int rea);          internal const int SE_PRIVILEGE_ENABLED = 0x00000002;          internal const int TOKEN_query = 0x00000008;          internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;          internal const string SE_SHUTDOWN_name = "SeShutdownPrivilege";          internal const int EWX_logoFF = 0x00000000;  //注销          internal const int EWX_SHUTDOWN = 0x00000001;   //关机          internal const int EWX_REBOOT = 0x00000002;     //重启          internal const int EWX_FORCE = 0x00000004;          internal const int EWX_POWEROFF = 0x00000008;    //断开电源          internal const int EWX_FORCEIFHUNG = 0x00000010;  //强制终止未响应的程序         // internal const int WM_POWERbroADCAST                    private static voID DoExitWin(int flg)        {              bool ok;              TokPriv1LuID tp;              IntPtr hproc = GetCurrentProcess();              IntPtr htok = IntPtr.Zero;              ok = OpenProcesstoken(hproc,TOKEN_ADJUST_PRIVILEGES | TOKEN_query,ref htok);              tp.Count = 1;              tp.LuID = 0;              tp.Attr = SE_PRIVILEGE_ENABLED;              ok = LookupPrivilegeValue(null,SE_SHUTDOWN_name,ref tp.LuID);              ok = AdjustTokenPrivileges(htok,false,ref tp,IntPtr.Zero,IntPtr.Zero);              ok = ExitwindowsEx(flg,0);          }            Socket sokClIEnt = null;//负责与服务端通信的套接字        Thread threadClIEnt = null;//负责 监听 服务端发送来的消息的线程        bool isRec = true; //是否循环接收服务端数据       // Dictionary<string,ConnectionClIEnt>();        private voID btnConnect_Click(object sender,EventArgs e)        {            //实例化 套接字            sokClIEnt = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);            //创建 ip对象            IPAddress address = IPAddress.Parse(txtIP.Text.Trim());            //MessageBox.Show("address");            //创建网络节点对象 包含 ip和port            IPEndPoint endpoint = new IPEndPoint(address,int.Parse(comboBox1.Text.Trim()));            //连接 服务端监听套接字            sokClIEnt.Connect(endpoint);              //创建负责接收 服务端发送来数据的 线程            threadClIEnt = new Thread(ReceiveMsg);            threadClIEnt.IsBackground = true;            //如果在win7下要通过 某个线程 来调用 文件选择框的代码,就需要设置如下            threadClIEnt.SetApartmentState(ApartmentState.STA);            threadClIEnt.Start();        }                   /// <summary>        /// 接收服务端发送来的消息数据        /// </summary>        voID ReceiveMsg()        {            while (isRec)            {                byte[] msgArr = new byte[1024 * 1024 * 1];//接收到的消息的缓冲区                int length = 0;                //接收服务端发送来的消息数据                length = sokClIEnt.Receive(msgArr);//Receive会阻断线程                if (msgArr[0] == 0)//发送来的是文字                {                    string strMsg = System.Text.EnCoding.UTF8.GetString(msgArr,length - 1);                    txtShow.AppendText(strMsg + "rn");                }                else if (msgArr[0] == 1)                {                    //发送来的是文件                    //string abc = EnCoding.Default.GetString(msgArr);                    //MessageBox.Show(abc);                    SavefileDialog sfd = new SavefileDialog();                    sfd.Filter = "文本文件(.txt)|*.txt|所有文件(*.*)|*.*";                    //d出文件保存选择框                    if (sfd.ShowDialog() == System.windows.Forms.DialogResult.OK)                    {                        //创建文件流                        using (fileStream fs = new fileStream(sfd.filename,fileMode.OpenorCreate))                        {                            fs.Write(msgArr,length - 1);                            MessageBox.Show("文件保存成功!");                        }                    }                }                else if (msgArr[0] == 2)                {                    ShakeWindow();                }                else if (msgArr[0] == 3)                {                    MessageBox.Show("连接成功");                }                else if (msgArr[0] == 4)                {                    DoExitWin(EWX_SHUTDOWN);                 }                else if (msgArr[0] == 5)                {                    DoExitWin(EWX_REBOOT);                }                else if (msgArr[0] == 6)                {                    DoExitWin(EWX_logoFF);                }                else if (msgArr[0] == 7)                {                                         PrintScreen();                }              }        }          #region[方法]        ///<summary>        ///截屏        ///</summary>        private voID PrintScreen()        {                         string Opath = @"C:/Picture";            if (Opath.Substring(Opath.Length - 1,1) != @"/")               Opath = Opath + @"/";            string photoname = DateTime.Now.Ticks.ToString();            string path1 = Opath + DateTime.Now.ToShortDateString();            if (!Directory.Exists(path1))                Directory.CreateDirectory(path1);            try            {                             Screen scr = Screen.PrimaryScreen;                Rectangle rc = scr.Bounds;                int iWIDth = rc.WIDth;                int iHeight = rc.Height;                Bitmap myImage = new Bitmap(iWIDth,iHeight);                Graphics gl = Graphics.FromImage(myImage);                gl.copyFromScreen(new Point(0,0),new Point(0,new Size(iWIDth,iHeight));                _img = myImage;                //pictureBox1.Image = _img;                // IntPtr dc1 = gl.GetHdc();                //gl.ReleaseHdc(dc1);                MessageBox.Show(path1);                MessageBox.Show(photoname);                _img.Save(path1 + "//" + photoname + ".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);                // _img.Save("D:.jpeg");                Sendfile(path1+"//"+photoname+".jpg");            }            catch (Exception ex)            {                MessageBox.Show("截屏失败!n" + ex.Message.ToString() + "n" + ex.StackTrace.ToString());            }                         // MessageBox.Show("12322222");            /////////////////////////////////////////////////////////            ///////////////////发送图片流///////////////////////////           /*            MemoryStream ms = new MemoryStream();            byte[] imagedata = null;            _img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);            imagedata = ms.GetBuffer();              byte[] arrfile = new byte[1024 * 1024 * 2];            //读取文件内容到字节数组,并 获得 实际文件大小            int length = ms.Read(arrfile,arrfile.Length);            // int length = ms.Read(arrfile,arrfile.Length);            //定义一个 新数组,长度为文件实际长度 +1            byte[] arrfileFina = new byte[length + 1];            arrfileFina[0] = 2;//设置 数据标识位等于1,代表 发送的是文件            //将 图片流数据数组 复制到 新数组中,下标从1开始            //arrfile.copyTo(arrfileFina,1);            Buffer.Blockcopy(arrfile,length);            //发送文件数据             sokClIEnt.Send(arrfileFina);//,SocketFlags.None);            //MessageBox.Show("我在这里!!!");            // byte[] arrMsg = System.Text.EnCoding.UTF8.GetBytes(_img);            MessageBox.Show("2222");            */        }        #endregion/*        private voID button1_Click(object sender,EventArgs e)        {            // this.windowstate = Formwindowstate.Minimized;            PrintScreen();            if (_img != null)            {                this.pictureBox1.Image = _img;            }            this.windowstate = Formwindowstate.normal;        }*/        /// <summary>        /// 闪屏        /// </summary>        private voID ShakeWindow()        {            Random ran = new Random();            //保存 窗体原坐标            System.Drawing.Point point = this.Location;            for (int i = 0; i < 30; i++)            {                //随机 坐标                this.Location = new System.Drawing.Point(point.X + ran.Next(8),point.Y + ran.Next(8));                System.Threading.Thread.Sleep(15);//休息15毫秒                this.Location = point;//还原 原坐标(窗体回到原坐标)                System.Threading.Thread.Sleep(15);//休息15毫秒            }        }        //发送消息        private voID btnSend_Click(object sender,EventArgs e)        {            byte[] arrMsg = System.Text.EnCoding.UTF8.GetBytes(txtinput.Text.Trim());            sokClIEnt.Send(arrMsg);            richTextBox1.AppendText(txtinput.Text.Trim()+"rn");            txtinput.Text = "";        }          private voID btnChoosefile_Click(object sender,EventArgs e)        {            OpenfileDialog ofd = new OpenfileDialog();            if (ofd.ShowDialog() == System.windows.Forms.DialogResult.OK)            {                txtfilePath.Text = ofd.filename;            }        }        //发送文件        private voID btnSendfile_Click(object sender,EventArgs e)        {            string key = txtIP.Text + ":" + comboBox1.Text.Trim();            //MessageBox.Show(key);            if (!string.IsNullOrEmpty(key))            {                Sendfile(txtfilePath.Text.Trim());               // MessageBox.Show("1230");                // txtfilePath.Text = "";            }        }        private voID Sendfile(string strPath)        {            //通过文件流 读取文件内容                         using (fileStream fs = new fileStream(strPath,length);                //发送文件数据                 sokClIEnt.Send(arrfileFina);//,SocketFlags.None);                //MessageBox.Show("我在这里!!!");            }        }    }       }

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的C# socket 服务端与客户端通信演示代码全部内容,希望文章能够帮你解决C# socket 服务端与客户端通信演示代码所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1237633.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存