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
        }
    }
}
相关推荐
娅娅梨18 分钟前
C++ 错题本--not found for architecture x86_64 问题
开发语言·c++
汤米粥24 分钟前
小皮PHP连接数据库提示could not find driver
开发语言·php
冰淇淋烤布蕾27 分钟前
EasyExcel使用
java·开发语言·excel
拾荒的小海螺33 分钟前
JAVA:探索 EasyExcel 的技术指南
java·开发语言
马剑威(威哥爱编程)1 小时前
哇喔!20种单例模式的实现与变异总结
java·开发语言·单例模式
白-胖-子1 小时前
【蓝桥等考C++真题】蓝桥杯等级考试C++组第13级L13真题原题(含答案)-统计数字
开发语言·c++·算法·蓝桥杯·等考·13级
好睡凯1 小时前
c++写一个死锁并且自己解锁
开发语言·c++·算法
java—大象1 小时前
基于java+springboot+layui的流浪动物交流信息平台设计实现
java·开发语言·spring boot·layui·课程设计
yyqzjw1 小时前
【qt】控件篇(Enable|geometry)
开发语言·qt
csdn_kike1 小时前
QT Unknown module(s) in QT 以及maintenance tool的更详细用法(qt6.6.0)
开发语言·qt