首页 > 编程语言 >C# 使用Socket实现长链接和短连接

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

时间:2023-07-21 18:14:42浏览次数:38  
标签:Socket C# Text System textBlock using 链接 clientSocket

直接上代码

服务端:

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
        }
    }
}

 

标签:Socket,C#,Text,System,textBlock,using,链接,clientSocket
From: https://www.cnblogs.com/log9527blog/p/17572107.html

相关文章

  • Spring Boot中内置Tomcat最大连接数、线程数与等待数 实践调优
    在SpringBoot框架中,我们使用最多的是Tomcat,这是SpringBoot默认的容器技术,而且是内嵌式的Tomcat。Tomcat是Apache基金下的一个轻量级的Servlet容器,支持Servlet和JSP。Tomcat服务器本身具有Web服务器的功能,可以作为独立的Web服务器来使用。一、SpringBoot应用......
  • K8S初始化报错:CRI v1 runtime API is not implemented for endpoint \"unix:///var/r
    报错具体内容:[preflight]Somefatalerrorsoccurred:[ERRORCRI]:containerruntimeisnotrunning:output:time="2023-07-21T09:20:07Z"level=fatalmsg="validateserviceconnection:CRIv1runtimeAPIisnotimplementedforendpoint\"un......
  • AddAuthentication
    // C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\7.0.5\Microsoft.AspNetCore.Authentication.dll// Microsoft.AspNetCore.Authentication, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60https://www.nuget.org/packages/Microsof......
  • LangChain: Tutorial: ChatGPT Over Your Data
    来源:   https://blog.langchain.dev/tutorial-chatgpt-over-your-data/     https://github.com/hwchase17/chat-your-dataHighLevelWalkthroughAtahighlevel,therearetwocomponentstosettingupChatGPToveryourowndata:(1)ingestionoftheda......
  • react批量生成pdf
    使用htmlpdf.js批量将html页面转为pdf,打包成zip下载。htmlpdf.js是结合html2canvas和jsPDF实现的。首先先安装包npminstall--savehtml2pdf.js基本页面importhtml2pdffrom"html2pdf.js";functionApp(){consthandleExportPdf=()=>{//导出pdf......
  • 财大ACM招新指南
    财大ACM实验室招新指南ACM科普大学竞赛ACM通俗是指XCPC,也就是ICPC/CCPC。其中ICPC即InternationalCollegiateProgrammingContest,它是国际大型比赛。也在中国高等教育学会列出的榜单上。属于国际竞赛。如果能在ICPC区域赛拿到银牌、金牌。国内的一些公司可能就会向你投......
  • Atcoder Regular Contest 154 E - Reverse and Inversion
    只要你发现是诈骗题就好办了。不要像我那样傻傻地瞪一个小时然后才发现那俩sigma里的东西相减是有性质的。先考虑计算单个\(f(p)\),一眼的树状数组……吗?考虑最终答案式子里\(i\)的系数:\(\sum\limits_{j<i}[p_j>p_i]-\sum\limits_{j>i}[p_j<p_i]\),因为\(\sum\limits_{j<i}[p......
  • 【问题解决】docker版本v23.0后,构建Dockerfile中FROM私库镜像报错构建失败
    问题情况Docker版本在v23.0以后,只要Dockerfile中FROM的私库镜像不存在本地,就会报错:#我本地是v24.0.2版本Docker[root@localhostipd]#dockerbuild.-tharbor.xxx.com.cn/test/bap:2.7.1[+]Building0.6s(3/3)FINISHED......
  • centos7中 aspera软件的安装
     01、系统[root@PC1home]#cat/etc/redhat-releaseCentOSLinuxrelease7.6.1810(Core) 02、conda安装[root@PC1test]#condainstall-chccaspera-cli-y 03、测试命令[root@PC1test]#aspera--versionIBMAsperaCLIversion3.9.6.1467.159c5b1......
  • 链接参数export dynamic和-rdynamic的使用
    存在程序main通过dlopen使用libA中的符号:main.c:1#include<stdio.h> 2#include<dlfcn.h> 3  4typedefvoid(*func)(void);  5  6  7voidtest_main() 8{ 9  return;10}11 12 13intmain()14{15  void*handle=dlopen("./libA.so",RTLD_N......