c#Socket通信基本使用

Posted huangxuqaq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#Socket通信基本使用相关的知识,希望对你有一定的参考价值。

基本流程

技术图片

Server

技术图片

技术图片
  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;
                //创建端口号对象
                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
            {

            }
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\\r\\n");
        }

        Socket socketSend;

        void Listen(object o)
        {
            Socket socketWatch = o as Socket;
            //等待客户端连接且创建一个负责通讯的socket
            while (true)
            {
                try
                {
                    //负责跟客户端通讯的socket 怎么存它?--下拉框
                    socketSend = socketWatch.Accept();
                    //将远程连接的客户端的(ip地址+端口号)和socket存入集合
                    disSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
                    //将远程连接的客户端的(ip地址+端口号)和socket存入下拉框中
                    cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
                    //例192.168.1.1:连接成功
                    ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功");
                    //开启一个新线程不停的接收客户端法发来的消息
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch
                {

                }
            }
        }

        //将远程连接的客户端的(ip地址+端口号)和socket存入集合
        Dictionary<string, Socket> disSocket = new Dictionary<string, Socket>();

        void Receive(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 Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        //服务器给客户端发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                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();
                //socketSend.Send(buffer);
                //获得用户在下拉框中选中的IP地址
                string ip = cboUsers.SelectedItem.ToString();
                disSocket[ip].Send(newBuffer);
            }
            catch
            {

            }
        }

        //选择要发送的文件
        private void btnSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\\Users\\xu.huang\\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();
                disSocket[cboUsers.SelectedItem.ToString()].Send(newBuffer, 0, r + 1, SocketFlags.None);
            }
        }

        private void btnZd_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] buffer = new byte[1];
                buffer[0] = 2;
                disSocket[cboUsers.SelectedItem.ToString()].Send(buffer);
            }
            catch
            {

            }
        }
View Code

Client

技术图片

技术图片
 Socket socketSend;

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //创建负责通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //拿到本机ip地址及端口号
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //获得要连接的服务器的ip地址及端口号
                socketSend.Connect(point);
                ShowMsg("连接成功");

                //开启一个新线程不停的接收服务器发来的消息
                Thread th = new Thread(Receive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {

            }
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\\r\\n");
        }

        //不停的接收服务器发来的消息
        void Receive()
        {
            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\\xu.huang\\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
                {

                }
            }
        }

        //客户端给服务器发送消息
        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }

        //取消跨线程检查
        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        //震动
        void Zd()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(200, 200);
                this.Location = new Point(300, 300);
            }
        }
View Code

 

以上是关于c#Socket通信基本使用的主要内容,如果未能解决你的问题,请参考以下文章

Python 之 Socket编程(TCP/UDP)

netty基本使用- socket通信

一起talk C栗子吧(第一百五十五回:C语言实例--获取socket通信地址)

C#Socket通信

谁能给个C语言socket 通信,用UDP协议的代码例子。。

C#socket通信-----多线程