欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# Socket 通信

程序员文章站 2022-07-07 15:16:10
...

服务端

Service.cs

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace csharpService
{
    public partial class Service : Form
    {
        public Service()
        {
            InitializeComponent();

            ///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消
            ///
            CheckForIllegalCrossThreadCalls = false;

            /// 获取本地IP
            textBox_current_address.Text = IPAddress.Any.ToString();
        }

        /// 创建一个字典,用来存储记录服务器与客户端之间的连接(线程问题)
        ///
        private Dictionary<string, Socket> clientList = new Dictionary<string, Socket>();

        /// 创建连接
        private void button_connect_Click(object sender, EventArgs e)
        {
            Thread myServer = new Thread(MySocket);
            //设置这个线程是后台线程
            myServer.IsBackground = true;
            myServer.Start();
        }

        //①:创建一个用于监听连接的Socket对象;
        //②:用指定的端口号和服务器的Ip建立一个EndPoint对象;
        //③:用Socket对象的Bind()方法绑定EndPoint;
        //④:用Socket对象的Listen()方法开始监听;
        //⑤:接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
        //⑥:通信结束后一定记得关闭Socket。

        /// 创建连接的方法
        private void MySocket()
        {
            //1.创建一个用于监听连接的Socket对象;
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

            //2.用指定的端口号和服务器的Ip建立一个EndPoint对象;
            IPAddress iP = IPAddress.Parse(textBox_current_address.Text);
            IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox_port.Text));

            //3.用Socket对象的Bind()方法绑定EndPoint;
            server.Bind(endPoint);

            //4.用Socket对象的Listen()方法开始监听;

            //同一时刻内允许同时加入链接的最大数量
            server.Listen(20);
            listBox_log.Items.Add("服务器已经成功开启!");

            //5.接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
            while (true)
            {
                //接受接入的一个客户端
                Socket connectClient = server.Accept();
                if (connectClient != null)
                {
                    string infor = connectClient.RemoteEndPoint.ToString();
                    clientList.Add(infor, connectClient);

                    listBox_log.Items.Add(infor + "加入服务器!");

                    ///服务器将消息发送至客服端
                    string msg = infor + "已成功进入到聊天室!";

                    SendMsg(msg);

                    //每有一个客户端接入时,需要有一个线程进行服务

                    Thread threadClient = new Thread(ReciveMsg);//带参的方法可以把传递的参数放到start中
                    threadClient.IsBackground = true;

                    //创建的新的对应的Socket和客户端Socket进行通信
                    threadClient.Start(connectClient);
                }
            }
        }

        /// 服务器接收到客户端发送的消息
        private void ReciveMsg(object o)
        {
            //Socket connectClient = (Socket)o; //与下面效果一样

            Socket connectClient = o as Socket;//connectClient负责客户端的通信
            IPEndPoint endPoint = null;
            while (true)
            {
                try
                {
                    ///定义服务器接收的字节大小
                    byte[] arrMsg = new byte[1024 * 1024];

                    ///接收到的信息大小(所占字节数)
                    int length = connectClient.Receive(arrMsg);

                    

                    if (length > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
                        //获取客户端的端口号
                        endPoint = connectClient.RemoteEndPoint as IPEndPoint;
                        //服务器显示客户端的端口号和消息
                        listBox_log.Items.Add(DateTime.Now + "[" + endPoint.Port.ToString() + "]:" + recMsg);

                        //服务器(connectClient)发送接收到的客户端信息给客户端
                        SendMsg("[" + endPoint.Port.ToString() + "]:" + recMsg);
                    }
                }
                catch (Exception)
                {
                    ///移除添加在字典中的服务器和客户端之间的线程
                    clientList.Remove(endPoint.ToString());

                    connectClient.Dispose();

                    


                }
            }
        }

        /// 服务器发送消息,客户端接收
        private void SendMsg(string str)
        {
            ///遍历出字典中的所有线程
            foreach (var item in clientList)
            {
                byte[] arrMsg = Encoding.UTF8.GetBytes(str);

                ///获取键值(服务器),发送消息
                item.Value.Send(arrMsg);
            }
        }
    }
}

C# Socket 通信

客户端

Client.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace csharp_Client
{
    public partial class Client : Form
    {
        public Client()
        {
            InitializeComponent();

            ///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消
            CheckForIllegalCrossThreadCalls = false;
        }

        /// 创建客户端
        private Socket client;

        private void button_connect_Click(object sender, EventArgs e)
        {
            ///创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ///IP地址
            IPAddress ip = IPAddress.Parse(textBox_address.Text);
            ///端口号
            IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(textBox_port.Text));
            ///建立与服务器的远程连接
            try
            { 
                client.Connect(endPoint);
            }
            catch(Exception)
            {
                MessageBox.Show("地址或端口错误!!!!");
                return;
            }
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
        }

        /// 客户端接收到服务器发送的消息
        private void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///定义客户端接收到的信息大小
                    byte[] arrList = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(arrList);
                    string msg = DateTime.Now + Encoding.UTF8.GetString(arrList, 0, length);
                    listBox_log.Items.Add(msg);
                }
                catch (Exception)
                {
                    ///关闭客户端
                    client.Close();
                }
            }
        }

        /// 客户端发送消息给服务端
        private void button_send_Click(object sender, EventArgs e)
        {
            if (textBox_message.Text != "")
            {
                SendMsg(textBox_message.Text);
            }
        }

        /// 客户端发送消息,服务端接收
        private void SendMsg(string str)
        {
            byte[] arrMsg = Encoding.UTF8.GetBytes(str);
            client.Send(arrMsg);
        }


        private void Client_FormClosed(object sender, FormClosedEventArgs e)
        {
            if(client!=null) client.Close();
        }
    }
}

C# Socket 通信

相关标签: c#