码迷,mamicode.com
首页 > Web开发 > 详细

体验.net core 3.1 socket

时间:2020-03-10 15:43:52      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:eric   image   idt   font   win   add   amp   sleep   core   

技术图片

 

 

最近好像比较闲了,每天也没加班经常不到半天就把活干完。7点半到公司,5点下班。这样的日子,好像也没意思。

想起把以前windows平台下的socket server程序试试在.net core下改造一下跑在linux服务器上。

services.AddSingleton(MiddlewareContext.GetInstance());
using DingTalk_Middleware.dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DingTalk_Middleware
{
    public class MiddlewareContext
    {
        private static MiddlewareContext _ServiceContext = null;
        private readonly static object lockObj = new object();
        public Dictionary<string, EmployeeDTO> UserCache = new Dictionary<string, EmployeeDTO>();
        protected Dictionary<string, Socket> clientDict = new Dictionary<string, Socket>();
        Action updateCacheTask;
        Socket serverSocket;
        Thread socketThread;
        private MiddlewareContext()
        {
            updateCacheTask = () =>
            {
                while (true)
                {
                    Console.WriteLine(DateTime.Now + ":->updateCacheTask is running!Cache Count:" + UserCache.Count + "");
                    System.Threading.Thread.Sleep(10000);
                    if (UserCache.Count > 1000)
                    {
                        UserCache.Clear();
                        Console.WriteLine(DateTime.Now + ":->Cache is cleared。");
                    }
                }
            };
            Task.Factory.StartNew(updateCacheTask);
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            byte[] inValue = new byte[] { 1, 0, 0, 0, 0x88, 0x13, 0, 0, 0xd0, 0x07, 0, 0 };
            serverSocket.IOControl(IOControlCode.KeepAliveValues, inValue, null);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5990);
            serverSocket.Bind(ipEndPoint);
            serverSocket.Listen(1024);
            socketThread = new Thread(() =>
            {
                if (serverSocket != null)
                {
                    while (true)
                    {
                        try
                        {
                            Socket clientSocket = serverSocket.Accept();
                            if (clientSocket != null)
                            {
                                string ip = clientSocket.RemoteEndPoint.ToString();
                                Console.WriteLine(DateTime.Now + "->:" + ip);
                                if (!clientDict.ContainsKey(ip))
                                {
                                    clientDict.Add(ip, clientSocket);
                                }
                                else
                                {
                                    clientDict[ip] = clientSocket;
                                }
                                Thread receiveThread = new Thread(ReceiveMessage);
                                receiveThread.Start(clientSocket);
                            }
                        }
                        catch
                        {
                        }
                        finally
                        {
                            Thread.Sleep(1);
                        }
                    }
                }
            });
            socketThread.Start();
        }

        private void ReceiveMessage(object clientSocket)
        {
            byte[] buffer = new byte[4096];
            Socket myClientSocket = (Socket)clientSocket;
            while (myClientSocket != null)
            {
                try
                {
                    if (myClientSocket != null && myClientSocket.Connected)
                    {
                        try
                        {
                            int receiveNumber = myClientSocket.Receive(buffer);
                            if (receiveNumber > 0)
                            {
                                string msg = Encoding.UTF8.GetString(buffer).Trim();
                                Console.WriteLine(DateTime.Now + "Recevice Data:->" + msg);
                            }
                        }
                        catch (Exception exx)
                        {
                            Console.WriteLine(Environment.NewLine + exx.Message);
                            if (myClientSocket != null)
                                myClientSocket.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(Environment.NewLine + ex.Message);
                }
                finally
                {
                    Thread.Sleep(10);
                }
            }
        }

        public static MiddlewareContext GetInstance()
        {
            if (_ServiceContext == null)
            {
                lock (lockObj)
                {
                    if (_ServiceContext == null)
                    {
                        _ServiceContext = new MiddlewareContext();
                    }
                }
            }
            return _ServiceContext;
        }
    }
}

不是控制台程序。就用的asp.net core webapi。这样api 和 socket server在一起,比较符合原来的场景。

 

体验.net core 3.1 socket

标签:eric   image   idt   font   win   add   amp   sleep   core   

原文地址:https://www.cnblogs.com/datacool/p/12455846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!