C# socket监听

来源:互联网 发布:正在安装虚拟网络驱动 编辑:程序博客网 时间:2024/06/05 15:29

网络通讯流程如上

服务器方面

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);        }    }}
二、建立客户端
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;        }        private void txtServer_TextChanged(object sender, EventArgs e)        {        }    }}



0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 小米手机充电没反应开不了机怎么办 红米note手机开不了机怎么办 红米手机突然黑屏开不了机怎么办 红米2a开不开机怎么办 红米4手开不了机怎么办 红米4a开不了机怎么办 魅族手机拨打电话时黑屏怎么办 金立手机拨打电话时黑屏怎么办 红米手机刷机黑屏了怎么办 酷派手机开机黑屏但能嗡嗡响怎么办 酷派手机忘记锁屏密码怎么办 酷派手机锁屏密码忘了怎么办 酷派手机不停的开机关机怎么办 苹果6手机进水了开不了机怎么办 金立手机突然黑屏开不了机怎么办 丢失手机又忘了ID锁怎么办? 小米2按出电话后黑屏怎么办 华为手机桌面拨号键没有了怎么办 华为荣耀5x黑屏后无法关机怎么办 华为手机突然黑屏电池充不了怎么办 华为手机恢复出厂设置后黑屏怎么办 华为荣耀畅玩6a内存不够怎么办 红米note4玩王者荣耀卡怎么办 华为荣耀5a手机被锁怎么办 华为荣耀v8应用锁忘记蜜码怎么办 阿里巴巴一键代销被投诉受假怎么办 登录小米云服务怎么删除密码怎么办 苹果6云空间连接不上怎么办 买家收到淘宝网交易异常通知怎么办 快递把我秒杀的货弄丢了怎么办 手机淘宝退货物流单号填错了怎么办 买家要求退货退款但是不发货怎么办 多给买家寄包裹不接电话怎么办 给买家发货物流单号错了怎么办 淘宝退货退款快递单号填错了怎么办 淘宝不小心点了延迟收货怎么办 淘宝快递地址错了货已经发了怎么办 卖家送运费险买家填错单号怎么办 买家无赖点了延迟收货卖家怎么办 淘宝卖家快递单号填错了怎么办 淘宝店有当天的快递忘记发货怎么办