国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#/.net學習-14-一個socket監管客戶端與服務端的小demo

2019-11-10 18:12:48
字體:
來源:轉載
供稿:網友

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 _07Client{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        Socket socketSend;        PRivate void btnStart_Click(object sender, EventArgs e)        {            try            {                //創建負責通信的Socket                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                ipAddress ip = IPAddress.Parse(txtServer.Text);                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));                //獲得要連接的遠程服務器應用程序的IP地址和端口號                socketSend.Connect(point);                ShowMsg("連接成功");                //開啟一個新的線程不停的接收服務端發來的消息                Thread th = new Thread(Recive);                th.IsBackground = true;                th.Start();            }            catch            { }                    }        /// <summary>        /// 不停的接受服務器發來的消息        /// </summary>        void Recive()        {            while (true)            {                try                {                    byte[] buffer = new byte[1024 * 1024 * 3];                    int r = socketSend.Receive(buffer);                    //實際接收到的有效字節數                    if (r == 0)                    {                        break;                    }                    //表示發送的文字消息                    if (buffer[0] == 0)                    {                        string s = Encoding.UTF8.GetString(buffer, 1, r-1);                        ShowMsg(socketSend.RemoteEndPoint + ":" + s);                    }                    else if (buffer[0] == 1)                    {                        SaveFileDialog sfd = new SaveFileDialog();                        sfd.InitialDirectory = @"C:/Users/SpringRain/Desktop";                        sfd.Title = "請選擇要保存的文件";                        sfd.Filter = "所有文件|*.*";                        sfd.ShowDialog(this);                        string path = sfd.FileName;                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, Fileaccess.Write))                        {                            fsWrite.Write(buffer, 1, r - 1);                        }                        MessageBox.Show("保存成功");                    }                    else if (buffer[0] == 2)                    {                        ZD();                    }                                }                catch { }            }        }        /// <summary>        /// 震動        /// </summary>        void ZD()        {            for (int i = 0; i < 500; i++)            {                this.Location = new Point(200, 200);                this.Location = new Point(280, 280);            }        }        void ShowMsg(string str)        {            txtLog.AppendText(str + "/r/n");        }        /// <summary>        /// 客戶端給服務器發送消息        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSend_Click(object sender, EventArgs e)        {            string str = txtMsg.Text.Trim();            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);            socketSend.Send(buffer);        }        private void Form1_Load(object sender, EventArgs e)        {            Control.CheckForIllegalCrossThreadCalls = false;        }    }}

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 _06Server{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void btnStart_Click(object sender, EventArgs e)        {            try            {                //當點擊開始監聽的時候 在服務器端創建一個負責監IP地址跟端口號的Socket                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                IPAddress ip = IPAddress.Any;//IPAddress.Parse(txtServer.Text);                //創建端口號對象                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));                //監聽                socketWatch.Bind(point);                ShowMsg("監聽成功");                socketWatch.Listen(10);                Thread th = new Thread(Listen);                th.IsBackground = true;                th.Start(socketWatch);            }            catch            { }        }        /// <summary>        /// 等待客戶端的連接 并且創建與之通信用的Socket        /// </summary>        ///         Socket socketSend;        void Listen(object o)        {            Socket socketWatch = o as Socket;            //等待客戶端的連接 并且創建一個負責通信的Socket            while (true)            {                try                {                    //負責跟客戶端通信的Socket                    socketSend = socketWatch.Accept();                    //將遠程連接的客戶端的IP地址和Socket存入集合中                    dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);                    //將遠程連接的客戶端的IP地址和端口號存儲下拉框中                    cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());                    //192.168.11.78:連接成功                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "連接成功");                    //開啟 一個新線程不停的接受客戶端發送過來的消息                    Thread th = new Thread(Recive);                    th.IsBackground = true;                    th.Start(socketSend);                }                catch                { }            }        }        //將遠程連接的客戶端的IP地址和Socket存入集合中        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();        /// <summary>        /// 服務器端不停的接受客戶端發送過來的消息        /// </summary>        /// <param name="o"></param>        void Recive(object o)        {            Socket socketSend = o as Socket;            while (true)            {                try                {                    //客戶端連接成功后,服務器應該接受客戶端發來的消息                    byte[] buffer = new byte[1024 * 1024 * 2];                    //實際接受到的有效字節數                    int r = socketSend.Receive(buffer);                    if (r == 0)                    {                        break;                    }                    string str = Encoding.UTF8.GetString(buffer, 0, r);                    ShowMsg(socketSend.RemoteEndPoint + ":" + str);                }                catch                { }            }        }        void ShowMsg(string str)        {            txtLog.AppendText(str + "/r/n");        }        private void Form1_Load(object sender, EventArgs e)        {            Control.CheckForIllegalCrossThreadCalls = false;        }        /// <summary>        /// 服務器給客戶端發送消息        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSend_Click(object sender, EventArgs e)        {            string str = txtMsg.Text;            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);            List<byte> list = new List<byte>();            list.Add(0);            list.AddRange(buffer);            //將泛型集合轉換為數組            byte[] newBuffer = list.ToArray();            //buffer = list.ToArray();不可能            //獲得用戶在下拉框中選中的IP地址            string ip = cboUsers.SelectedItem.ToString();            dicSocket[ip].Send(newBuffer);            //     socketSend.Send(buffer);        }        /// <summary>        /// 選擇要發送的文件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnSelect_Click(object sender, EventArgs e)        {            OpenFileDialog ofd = new OpenFileDialog();            ofd.InitialDirectory = @"C:/Users/SpringRain/Desktop";            ofd.Title = "請選擇要發送的文件";            ofd.Filter = "所有文件|*.*";            ofd.ShowDialog();            txtPath.Text = ofd.FileName;        }        private void btnSendFile_Click(object sender, EventArgs e)        {            //獲得要發送文件的路徑            string path = txtPath.Text;            using (FileStream fsRead = new FileStream(path, FileMode.Open, FileAccess.Read))            {                byte[] buffer = new byte[1024 * 1024 * 5];                int r = fsRead.Read(buffer, 0, buffer.Length);                List<byte> list = new List<byte>();                list.Add(1);                list.AddRange(buffer);                byte[] newBuffer = list.ToArray();                dicSocket[cboUsers.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);            }        }        /// <summary>        /// 發送震動        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void btnZD_Click(object sender, EventArgs e)        {            byte[] buffer = new byte[1];            buffer[0] = 2;            dicSocket[cboUsers.SelectedItem.ToString()].Send(buffer);        }    }}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通河县| 姜堰市| 新闻| 浙江省| 赣州市| 从江县| 南阳市| 镇原县| 汉阴县| 枣庄市| 越西县| 临夏市| 贡嘎县| 达尔| 错那县| 汉川市| 安义县| 河间市| 海原县| 清苑县| 周至县| 抚顺县| 繁昌县| 舒兰市| 始兴县| 新和县| 阿荣旗| 万年县| 克东县| 浏阳市| 无锡市| 商水县| 泌阳县| 岢岚县| 铜山县| 新和县| 合作市| 响水县| 临朐县| 赤水市| 喀什市|