• C# Winform界面 Socket编程


     

    ----

    重要方法:
    IPAddress ip = IPAddress.Any;//服务端设置
    IPAddress ip = IPAddress.Parse(IP地址);//IP对象
    IPEndPoint point = new IPEndPoint(ip,端口号);//设置端口号和IP;
    Socket socket = new Socket(AddressFamily.InterNetwork,SockType.Stream,PotocolType.Tcp);
    Socket.Connect(point);//客户端连接服务器;
    Socket.Bind(Point); //服务端绑定端口;
    Socket.Listen() ;//服务端设置监听数据长度;
    Socket.Accept();//等待客户端连接,创建客户端Socket对象;
    Socket.Receive();//接收客户端传来的消息;
    Encoding.UTF8.GetString();//将字节转换成字符串;
    Socket.Send(buffer);//消息发送:发送字节组;

    ---

    服务器:

    1、设置服务器:端口 、IP;

          IPAddress ip = IPAddress.Parse("IP地址");//设置ip地址对象
          IPEndPoint point = new IPEndPoint(ip,端口号[int]); //设置端口号和ip

    2、设置服务器:Socket 通信对象;

         Socket socketwatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

    3、服务器Socket绑定 端口 和 IP;

         sockwatch.Bind(point);

    4、设置服务器监听数据长度,0表示无限;

    sockwatch.listen(0);

    5、服务器Socket等待客户端连接,并创建客户端通信对象。

         Socket socketsend = socketwatch.accept();

    6、接收客户端上传消息。

          byte[]buffer=new byte[1024*1024*2];
          int r= socketsend.Receive(buffer); //将接收的数据赋值到 字节组 buffer数组中;
          string str = Encoding.UTF8.GetString(buffer,0,r); //将字节转换为字符串; 

    ====================================================================================

    客户端:


    1、设置服务器端口和IP;

    IPAddress ip = IPAddress.Parse("ip地址"); //服务器IP
    IPEndPoint point = new IPEndPoint(ip,端口号); //服务器端口和IP

    2、创建客户端Socket对象;

    Socket socksend = new Socket(AddressFamily.InerNetwork,SocketType.Stream,ProtocolType.Tcp);

    3、连接服务器;

    socksend.Connect(point);//连接服务器

    4、接收服务器传输数据;

    byte []buffer = new byte[1024*1024*2];
    int r = socketsend.Receive(buffer); //填充字节组,获取字节长度;
    string str = EnCoding.UTF8.GetString(buffer,0,r);//将字节数据组转换为字符串;

    ====================================================================================

    服务端代码

        public partial class FormServer : Form
        {
            public FormServer()
            {
                InitializeComponent();
            }
            //声明 socketSend 用于等待客户端的连接 并且创建与之通信用的SocketSend,//等客户端连接//接受到client连接,为此连接建立新的socket,并接受信息
            Socket socketSend;
            //将远程连接的客户端的IP地址和Socket存入集合中
            Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
            void ShowMsg(string str)//给消息文本框加文本的方法
            {
                txtLog.AppendText(str + "
    ");
            }
            /// <summary>
            /// 
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void btnStart_Click(object sender, EventArgs e)
            {
                try
                {
                    IPAddress ip = IPAddress.Any;
                    IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//创建终结点(EndPoint)             
                    Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立监视的Socket
                    socketWatch.Bind(point);//使得Socket绑定Bind()端口,参数为EndPoint//监听
                    ShowMsg("监听成功");
                    socketWatch.Listen(0);//参数是监听的最大长度,0是无限
                    Thread th = new Thread(Listen);//新建线程,运行soketWatch(),这里的Listen是自定义的方法
                    th.IsBackground = true;//线程为后台属性
                    th.Start(socketWatch);//提供线程要执行的方法的要使用的数据(参数)的对象
                }
                catch
                { }
            }
            //被线程执行的函数,用于Accept()新建Socket,把每次的新建Socket,添加RemoteEndPoint到Dic集合,添加到cbo下拉列表框,有参数的话,必须是object类型
            void Listen(object o)
            {
                Socket socketWatch = o as Socket;//as 强转语句,object o参数强转为Socket类型
                while (true)
                {
                    try
                    {
                        /*---------主要代码----------------*/
                        socketSend = socketWatch.Accept();//等待客户端的连接 并且创建一个负责通信的Socket             
                        dicSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);//将远程连接的客户端的IP地址和Socket存入集合中
                        /*---------主要代码----------------*/
    
                        Action<string> action = (data) =>
                        {
                            cboUsers.Items.Add(data);
                        };
                        Invoke(action, socketSend.RemoteEndPoint.ToString());
                        ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");//192.168.11.78:连接成功
    
                        /*---------主要代码----------------*/
                        Thread th = new Thread(Recive);//开启 一个新线程不停的接受客户端发送过来的消息
                        th.IsBackground = true;
                        th.Start(socketSend);
                        /*---------主要代码----------------*/
                    }
                    catch
                    {
    
                    }
                }
            }
            /// <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
                    { }
                }
            }
            private void btnSelect_Click(object sender, EventArgs e)// 选择要发送的文件
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = @"C:UsersSpringRainDesktop";
                ofd.Title = "请选择要发送的文件";
                ofd.Filter = "所有文件|*.*";
                ofd.ShowDialog();
                txtPath.Text = ofd.FileName;
            }
    
            //自定义协议,在传递的字节数组前面加上一个字节作为标识,0表示文字,1表示文件,2表示震动
            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
                list.Add(0);//是自定义协议,在传递的字节数组前面加上一个字节作为标识,0表示文字,1表示文件
                list.AddRange(buffer);//添加buffer数组进集合list
                byte[] newBuffer = list.ToArray();//将泛型集合转换为数组
                string ip = cboUsers.SelectedItem.ToString(); //获得用户在下拉框中选中的IP地址
                dicSocket[ip].Send(newBuffer);//Socket.Send()将数据发送到连接的Socket//socketSend.Send(buffer); 
            }
    
            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);
            }
    
    
    
    
    
        }

    客户端代码

        public partial class FormClient : Form
        {
            public Socket socketSend;
            public FormClient()
            {
                InitializeComponent();
            }
    
            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);
                    this.label3.Text = "连接状态:"+"连接成功";// 连接状态: 
                    //开启一个新的线程不停的接收服务端发来的消息
                    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:UsersSpringRainDesktop";
                            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 + "
    ");
            }
    
            /// <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);
            }
        }

     源码:https://files.cnblogs.com/files/lanyubaicl/CSocket.zip

  • 相关阅读:
    后缀数组
    网络流 HOJ1087
    备用
    css-具有缩略图的材料列表
    正则匹配log行
    vue-cli的webpack打包,icon无法正确加载
    导出CSV,导出excel数字过长显示科学计数法解决方案
    js导出CSV
    git常见操作指令
    javascript原型的意义
  • 原文地址:https://www.cnblogs.com/lanyubaicl/p/11059519.html
Copyright © 2020-2023  润新知