C# 使用Socket实现长链接和短连接

直接上代码

服务端:

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

namespace SocketServer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        private byte[] _result = new byte[1024];

        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            SocketService();
        }

        public void SocketService()
        {
            textBlock.Text +=  ("服务端已启动");
            var host = "127.0.0.1";
            var port = 5000;
            _socket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
            _socket.Listen(10); // 设定最多10个排队连接请求
            Task.Run(ListenClientConnect);
        }

        private void ListenClientConnect()
        {
            while (true)
            {
                var clientSocket = _socket.Accept();
                clientSocket.Send(Encoding.UTF8.GetBytes("我是服务器"));
                var receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientSocket);
            }
        }

        private void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientSocket接收数据  
                    int receiveNumber = myClientSocket.Receive(_result);
                    if (receiveNumber == 0)
                        return;
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        textBlock.Text += string.Format("接收客户端{0} 的消息:{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(_result, 0, receiveNumber));
                    });
                    
                    //给Client端返回信息
                    string sendStr = "已成功接到您发送的消息";
                    byte[] bs = Encoding.UTF8.GetBytes(sendStr);//Encoding.UTF8.GetBytes()不然中文会乱码
                    myClientSocket.Send(bs, bs.Length, 0);  //返回信息给客户端
                    //myClientSocket.Close(); //发送完数据关闭Socket并释放资源//长连接的话就不关闭
                    //Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        textBlock.Text += (ex.Message);
                    });
                    myClientSocket.Close();//关闭Socket并释放资源
                    //myClientSocket.Shutdown(SocketShutdown.Both);//禁止发送和上传
                    break;
                }
            }
        }
    }
}

客户端:

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

namespace SocketClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            ShotLink("321");
            // LongLink();
        }

        /// <summary>
        /// 短连接,最后调用Close释放资源
        /// </summary>
        /// <param name="input"></param>
        private void ShotLink(string input)
        {
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 5000)); //配置服务器IP与端口  
                textBlock.Text +=  ("连接服务器成功");
            }
            catch
            {
                textBlock.Text +=  ("连接服务器失败!");
                return;
            }

            string sendMessage = "你好";//发送到服务端的内容
            clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));//向服务器发送数据,需要发送中文则需要使用Encoding.UTF8.GetBytes(),否则会乱码
            textBlock.Text +=  ("向服务器发送消息:" + sendMessage);

            //接受从服务器返回的信息
            string recvStr = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0);    //从服务器端接受返回信息 
            recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
            textBlock.Text +=  string.Format("服务端发来消息:{0}", recvStr);//回显服务器的返回信息
            //每次完成通信后,关闭连接并释放资源
            clientSocket.Close();
            Console.ReadLine();
        }


        /// <summary>
        /// 长连接不调用Close释放资源
        /// </summary>
        private void LongLink()
        {
            //设定服务器IP地址  
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 5000)); //配置服务器IP与端口  
                textBlock.Text +=  ("连接服务器成功");
            }
            catch
            {
                textBlock.Text +=  ("连接服务器失败");
                return;
            }

            //循环读取输入数据
            while (true)
            {
                textBlock.Text +=  ("请输入");
                string sentstr = "123";
                SentMsg(sentstr, clientSocket);
                Thread.Sleep(5000);
            }
        }


        /// <summary>
        /// 长连接,不释放资源
        /// </summary>
        /// <param name="sentstr"></param>
        /// <param name="clientSocket"></param>
        private void SentMsg(string sentstr, Socket clientSocket)
        {
            string sendMessage = "你好";//发送到服务端的内容
            sendMessage = sentstr;//发送到服务端的内容
            //向服务器发送数据,需要发送中文则需要使用Encoding.UTF8.GetBytes(),否则会乱码
            clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));
            textBlock.Text +=  ("向服务器发送消息:" + sendMessage);

            //接受从服务器返回的信息
            string recvStr = "";
            byte[] recvBytes = new byte[1024];
            int bytes;
            bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0);    //从服务器端接受返回信息 
            recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes);
            textBlock.Text +=  string.Format("服务端发来消息:{0}", recvStr);    //回显服务器的返回信息
            //clientSocket.Close();//关闭连接并释放资源//如果是长连接,注释掉close
        }
    }
}

 

posted @ 2023-07-21 17:52  log9527  阅读(617)  评论(0编辑  收藏  举报