C#一个服务器端多个客户端Socket通信

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32832727/article/details/78289648

原理:

启动服务端后,服务端通过持续监听客户端发来的请求,一旦监听到客户端传来的信息后,两端便可以互发信息了。服务器端需要绑定一个IP和端口号,用于客户端在网络中寻找并建立连接。信息发送原理:将手动输入字符串信息转换成机器可以识别的字节数组,然后调用套接字的Send()方法将字节数组发送出去。信息接收原理:调用套接字的Receive()方法,获取对端传来的字节数组,然后将其转换成人可以读懂的字符串信息。


服务器端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketTest
{
    public partial class FormServer : Form
    {
        Socket socketListen;//用于监听的socket
        Socket socketConnect;//用于通信的socket
        string RemoteEndPoint;     //客户端的网络节点  
        Dictionary<string, Socket> dicClient = new Dictionary<string, Socket>();//连接的客户端集合
        public FormServer()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartSocket();
        }
        public void StartSocket()
        {
            //创建套接字
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(textBox_ip.Text), int.Parse(textBox_port.Text));
            socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定端口和IP
            socketListen.Bind(ipe);
            //设置监听
            socketListen.Listen(10);
            //连接客户端
            AsyncConnect(socketListen);
        }

        /// <summary>
        /// 连接到客户端
        /// </summary>
        /// <param name="socket"></param>
        private void AsyncConnect(Socket socket)
        {
            try
            {
                socket.BeginAccept(asyncResult =>
            {
                //获取客户端套接字
                socketConnect = socket.EndAccept(asyncResult);
                RemoteEndPoint = socketConnect.RemoteEndPoint.ToString();
                dicClient.Add(RemoteEndPoint, socketConnect);//添加至客户端集合
                comboBox1.Items.Add(RemoteEndPoint);//添加客户端端口号
                AsyncSend(socketConnect, string.Format("欢迎你{0}", socketConnect.RemoteEndPoint));
                AsyncReceive(socketConnect);
                AsyncConnect(socketListen);
            }, null);


            }
            catch (Exception ex)
            {

            }

        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="client"></param>
        private void AsyncReceive(Socket socket)
        {
            byte[] data = new byte[1024];
            try
            {
                //开始接收消息
                socket.BeginReceive(data, 0, data.Length, SocketFlags.None,
                asyncResult =>
                {
                    try
                    {
                        int length = socket.EndReceive(asyncResult);
                        setText(Encoding.UTF8.GetString(data));
                    }
                    catch (Exception)
                    {
                        AsyncReceive(socket);
                    }

                    AsyncReceive(socket);
                }, null);

            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="client"></param>
        /// <param name="p"></param>
        private void AsyncSend(Socket client, string message)
        {
            if (client == null || message == string.Empty) return;
            //数据转码
            byte[] data = Encoding.UTF8.GetBytes(message);
            try
            {
                //开始发送消息
                client.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    //完成消息发送
                    int length = client.EndSend(asyncResult);
                }, null);
            }
            catch (Exception ex)
            {
                //发送失败,将该客户端信息删除
                string deleteClient = client.RemoteEndPoint.ToString();
                dicClient.Remove(deleteClient);
                comboBox1.Items.Remove(deleteClient);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1)
            {
                AsyncSend(socketConnect, textBox2.Text);
            }
            else
            {
                AsyncSend(dicClient[comboBox1.SelectedItem.ToString()], textBox2.Text);
            }

        }
        private void setText(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(() => setText(str)));
            }
            else
            {
                textBox1.Text += "\r\n" + str;
            }
        }

    }
}



客户端代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;


namespace SocketClient
{
    public partial class FormClient : Form
    {
        Socket client;
        public FormClient()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            AsyncConnect();
        }

        /// <summary>
        /// 连接到服务器
        /// </summary>
        public void AsyncConnect()
        {
            try
            {
                //端口及IP
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(textBox_ip.Text), int.Parse(textBox_port.Text));
                //创建套接字
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //开始连接到服务器
                client.BeginConnect(ipe, asyncResult =>
                {
                    client.EndConnect(asyncResult);
                    //向服务器发送消息
                    AsyncSend(client, "你好我是客户端");
                    //接受消息
                    AsyncReceive(client);
                }, null);
            }
            catch (Exception ex)
            {

            }


        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="message"></param>
        public void AsyncSend(Socket socket, string message)
        {
            if (socket == null || message == string.Empty) return;
            //编码
            byte[] data = Encoding.UTF8.GetBytes(message);
            try
            {

                socket.BeginSend(data, 0, data.Length, SocketFlags.None, asyncResult =>
                {
                    //完成发送消息
                    int length = socket.EndSend(asyncResult);
                }, null);
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="socket"></param>
        public void AsyncReceive(Socket socket)
        {
            byte[] data = new byte[1024];
            try
            {

                //开始接收数据
                socket.BeginReceive(data, 0, data.Length, SocketFlags.None,
                asyncResult =>
                {
                    try
                    {
                        int length = socket.EndReceive(asyncResult);
                        setText(Encoding.UTF8.GetString(data));
                    }
                    catch (Exception)
                    {
                        AsyncReceive(socket);
                    }


                    AsyncReceive(socket);
                }, null);
            }
            catch (Exception ex)
            {
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AsyncSend(client, textBox2.Text);
        }
        private void setText(string str)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new MethodInvoker(() => setText(str)));
            }
            else
            {
                textBox1.Text += "\r\n" + str;
            }
        }

    }
}

效果图:


猜你喜欢

转载自blog.csdn.net/sinat_32832727/article/details/78289648