A simple control and client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Configuration;
using System.Reflection;
using Common.MySocket;

namespace ControlCenter
{
    class Program
    {

        public static Dictionary<string, Socket> socketDC = new Dictionary<string, Socket>();
        public static Dictionary<string, bool> sendFlag = new Dictionary<string, bool>();
        public static Dictionary<string, bool> recvFlag = new Dictionary<string, bool>();
        //client is ok or not 
        public static Dictionary<string, bool> clientflag = new Dictionary<string, bool>();
        private static byte[] result = new byte[1024];
        //private static Queue<String> myQueue = new Queue<String>();
        static List<string> commands = new List<string>();
        static List<string> innercommands = new List<string>();
        //do command(such as listcase, listtask)
        static bool IsCommand = false;
        static int MAXSPAN = 60000;

        static ServerSocket ssocket;

        static volatile bool DoingFlag = false;

        //process log
        static List<string> logDC = new List<string>();

        static void Main(string[] args)
        {
            //init socket and command
            Init();

            //start a thread ,accept new connection
            Thread myThread = new Thread(ListenClientConnect);
            myThread.IsBackground = true;
            myThread.Start();

            //now wait for commands
            Console.WriteLine("please input your command :");
            string[] inputcommands;
            int mycount = 1;
            while (true)
            {
                //read from keyboard
                mycount = 1;
                string mycommand = Console.ReadLine();
                if (mycommand.Contains(':'))
                {
                    inputcommands = mycommand.Split(':');
                    mycommand = inputcommands[0];
                    mycount = int.Parse(inputcommands[1]);
                }
                mycommand  =  mycommand.ToUpper();

                //command exit, exit main thread,end program
                if (mycommand == "EXIT") { CloseClients();  break; }

                //heartbeat packet, test clients is ok or not, if ok, set it to clientflag
                SendHelloMessage("HELLO");
                
                //process inner commands
                bool IsInnerCmd = ProcessInnerCommand(mycommand);

                //Determine whether there exists clients
                if (clientflag.Count > 0 )
                {
                    //not inner command,such (exit,list etc.), we need send it to clients
                    if (!IsInnerCmd)
                    {
                        //send the command, let test clients prepare well
                        IsCommand = false;
                        //is the command in our command list?
                        foreach (var command in commands)
                        {
                            if (command.ToUpper() == mycommand)
                            {
                                IsCommand = true;
                                //there is flag for doing
                                if (!DoingFlag)
                                {
                                    DoingFlag = true;
                                    int sendCount = 0;
                                    if (mycount > 0)
                                    {
                                        sendCount = SendCommand(command+":"+mycount);
                                    }
                                    else
                                    {
                                        sendCount = SendCommand(command);
                                    }
                                    int recvConut = RecveResponseCommand();
                                    if (recvConut != sendCount)
                                    {
                                        Console.WriteLine("recvcount:{0}-----sendcount:{1}", recvConut, sendCount);
                                    }
                                    //after prepare well(send back the result), send start command
                                    sendCount = SendCommand("START");
                                    Console.WriteLine("Start test ");

                                    //start a new thread to receive response result, do not block main block
                                    Thread receiveThread = new Thread(RecvResult);
                                    receiveThread.IsBackground = true;
                                    receiveThread.Start();
                                }
                            }
                        }
                        if (!IsCommand)
                        {
                            Console.WriteLine("the command {0} is not in the command list, please check your configure", mycommand);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("There are no connected clients, please start clients-- clientflag.Count {0}", clientflag.Count);
                }
            }
        }

        private static bool Init()
        {
            IPAddress ServerIP = null ;
            int ServerPort;
            int QueueNum;

            #region  get ip
            //get ip, if not set default
            try
            {
                ServerIP = IPAddress.Parse(ConfigurationManager.AppSettings["ServerIP"]);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Server IP is wrong {0}", ex.Message);
            }
            if (ServerIP == null)
            {
                ServerIP = IPAddress.Parse("172.16.73.127");
            }
            #endregion

            #region  get port
            //get port,if not set default
            try
            {
                ServerPort = int.Parse(ConfigurationManager.AppSettings["ServerPort"]);
                if (ServerPort > 65536 || ServerPort <= 1024)
                {
                    ServerPort = 8888;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Server port is wrong {0}", ex.Message);
                ServerPort = 8888;
            }
            #endregion

            #region get queue number
            try
            {
                QueueNum = int.Parse(ConfigurationManager.AppSettings["QueueNum"]);
                if (QueueNum > 10000 || QueueNum < 1000)
                {
                    QueueNum = 5000;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Queue number is not set {0}", ex.Message);
                QueueNum = 5000;
            }
            #endregion

            //start socket
            try
            {
                ssocket = new ServerSocket(ServerIP, ServerPort);
                ssocket.Init(QueueNum);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error message : {0}",ex.Message);
                return false;
            }

            //init comand list
            int count = InitCommand();
            if (count == 0)
            {
                Console.WriteLine("There are no commands");
                return false;
            }
            return true;
        }

        private static int  InitCommand()
        {
            try
            {
                commands = ConfigurationManager.AppSettings["Commands"].Split(',').ToList<string>();
                //foreach (var command in commands)
                //{
                //    Console.WriteLine("command : {0}", command);
                //}
                return commands.Count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("init command exception : ", ex.Message);
                return commands.Count;
            }
        }

        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket scsocket = ssocket.AcceptSocket();
                Console.WriteLine("remote point {0}--- local point:{1} ", scsocket.RemoteEndPoint.ToString(), scsocket.LocalEndPoint.ToString());
                socketDC.Add(scsocket.RemoteEndPoint.ToString(), scsocket);
            }
        }

        private static bool ProcessInnerCommand(string mycommand)
        {
                bool IsInnerFlag = false;
                //list all connections
                if (mycommand == "LIST")
                {
                    IsInnerFlag = true;
                    ShowConnectList();
                }

                //list all commands
                else if (mycommand == "COMMAND")
                {
                    IsInnerFlag = true;
                    ShowComamndList();
                }

                //close all clients
                else if (mycommand == "END" || mycommand =="CLOSE")
                {
                    IsInnerFlag = true;
                    CloseClients();
                }
                else if (mycommand == "CALC")
                {
                    CalcResult();
                    IsInnerFlag = true;
                }
                return IsInnerFlag;
        }

        private static void ShowConnectList()
        {
            foreach (var obj in socketDC)
            {
                if (clientflag.ContainsKey(obj.Key))
                {
                    Console.WriteLine("{0}:{1}", obj.Key, obj.Value);
                }
            }
        }

        private static void SendHelloMessage(String hello)
        {
            List<string> allkeys = new List<string>(socketDC.Keys);
            if (allkeys.Count == 0)
            {
                Console.WriteLine("There are no connected clients, please start clients");
                return;
            }
            clientflag.Clear();
            foreach (var key in allkeys)
            {
               // Console.WriteLine("keys :{0}:{1}", key, socketDC[key]);

                try
                {
                    if (socketDC[key].Connected)
                    {
                        socketDC[key].Send(Encoding.ASCII.GetBytes(hello));
                        int receiveNumber = socketDC[key].Receive(result);
                        if (receiveNumber > 0)
                        {
                            String str = Encoding.ASCII.GetString(result, 0, receiveNumber);
                                clientflag.Add(key,true);
                            Console.WriteLine("222 receive hello message::{0} from {1}", str,key);
                        }
                    }
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine("::{0}", ex.Message);
                    if (socketDC[key].Connected)
                    {
                        socketDC[key].Shutdown(SocketShutdown.Both);
                        socketDC[key].Close();
                    }
                    socketDC.Remove(key);
                }
            }
        }

        private static int SendCommand(string command)
        {
            List<string> allkeys = new List<string>(socketDC.Keys);
            sendFlag.Clear();
            foreach (var key in allkeys)
            {
                //Console.WriteLine("keys :{0}:{1}", key, socketDC[key]);
                try
                {
                    if (socketDC[key].Connected)
                    {
                        socketDC[key].Send(Encoding.ASCII.GetBytes(command));
                        sendFlag.Add(key, true);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("::{0}", ex.Message);
                    if (socketDC[key].Connected)
                    {
                        socketDC[key].Shutdown(SocketShutdown.Both);
                        socketDC[key].Close();
                    }
                    socketDC.Remove(key);
                }
            }
            return sendFlag.Count;
        }

        private static int RecveResponseCommand()
        {
            recvFlag.Clear();
            //Set the timeout time
            DateTime dt = DateTime.Now;

            while (true)
            {
                Thread.Sleep(20);
                List<string> allkeys = new List<string>(sendFlag.Keys);
                if (sendFlag.Count != 0)
                {
                    foreach (var key in allkeys)
                    {
                        try
                        {
                            if (socketDC[key].Connected)
                            {
                                Array.Clear(result, 0, result.Length);
                                int receiveNumber = socketDC[key].Receive(result);
                                if (receiveNumber > 0)
                                {
                                    String str = Encoding.ASCII.GetString(result, 0, receiveNumber);
                                    recvFlag.Add(key, true);
                                    sendFlag.Remove(key);
                                    Console.WriteLine("111 receive response message::{0}", str);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("::{0}", ex.Message);
                            if (socketDC[key].Connected)
                            {
                                socketDC[key].Shutdown(SocketShutdown.Both);
                                socketDC[key].Close();
                            }
                            socketDC.Remove(key);
                            sendFlag.Remove(key);
                        }
                    }
                }
                else 
                {
                    break;
                }
                TimeSpan ts = DateTime.Now - dt;
                if (ts.TotalMilliseconds > MAXSPAN)
                {
                    Console.WriteLine("timespan :: {0}", ts.TotalMilliseconds);
                    break;
                }
            }
            return recvFlag.Count;
        }

        private static void RecvResult()
        {
            int totalsocket = sendFlag.Count;
            List<Socket> allsockets = new List<Socket>();
            List<Socket> temp ;
            logDC.Clear();

            foreach (var key in sendFlag.Keys)
            {
                allsockets.Add(socketDC[key]);
            }

            while (true)
            {
                temp = new List<Socket>(allsockets);
                try
                {
                    if (totalsocket > 0)
                    {
                        Socket.Select(temp, null, null, 1000);
                        int count = temp.Count;
                        for (int i = 0; i < count; i++)
                        {
                            int receiveNumber = temp[i].Receive(result);
                            if (receiveNumber > 0)
                            {
                                String str = Encoding.ASCII.GetString(result, 0, receiveNumber);
                                logDC.Add(str);
                                Console.WriteLine("result 4444 :: receive response message::{0}", str);
                            }
                            else
                            {
                                temp[i].Shutdown(SocketShutdown.Both);
                                temp[i].Close();
                                allsockets.Remove(temp[i]);
                                Console.WriteLine("result:: error::{0}");
                            }
                            totalsocket--;
                        }
                    }
                    else { DoingFlag = false; break; }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("last ::{0}", ex.Message);
                    Thread.Sleep(1000);
                }
            }
        }

        private static void CloseClients()
        {
            foreach (var obj in socketDC)
            {
                if (clientflag.ContainsKey(obj.Key) && obj.Value.Connected)
                {
                    Console.WriteLine("{0}:{1}", obj.Key, obj.Value);
                    obj.Value.Send(Encoding.ASCII.GetBytes("CLOSE"));
                    obj.Value.Shutdown(SocketShutdown.Both);
                    obj.Value.Close();
                }
            }
        }

        private static void ShowComamndList()
        {
            foreach (var obj in commands)
            {
                    Console.WriteLine("{0}", obj);
            }
        }


        private static void CalcResult()
        {
            if (logDC.Count > 0)
            {
                string[] strs = null;
                double everytime = 0;
                foreach (var log in logDC)
                {
                    strs = log.Split(',');
                    Console.WriteLine("client ip:{0}, total send :{1}, total time:{2}", strs[0], strs[1], strs[2]);
                    int count = int.Parse(strs[1]);
                    long time = long.Parse(strs[2]);
                    if (count > 0)
                    {
                        everytime += count / (time / 1000.0);
                    }
                }
                Console.WriteLine("Every time : {0} ", everytime);
            }
            else
            {
                Console.WriteLine("no log ");
            }
        }
        
    }
}

 clietn :

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;  
using System.Net.Sockets;  
using System.Threading;
using System.Reflection;

namespace ClientRunner
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static volatile bool startFlag = false;

        static void Main(string[] args)
        {
            Socket clientSocket;
            try
            {
                IPAddress ip = IPAddress.Parse("127.0.0.1");
                int port = 8888;
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(new IPEndPoint(ip, 8888));
                Console.WriteLine("connect ip:{0}--port:{1} success, myself is {2}", ip, port, clientSocket.LocalEndPoint.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("failure! : {0}", ex.Message);
                return;
            }

            Thread receiveThread = new Thread(ReceiveMessage);
            //receiveThread.IsBackground = true;
            receiveThread.Start(clientSocket);
        }

        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    int receiveNumber = myClientSocket.Receive(result);
                    if (receiveNumber > 0)
                    {
                        String str = Encoding.ASCII.GetString(result, 0, receiveNumber);
                        Console.WriteLine("receive {0} message {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
                        if (str == "CLOSE")
                        {
                            break;
                        }
                        ProcesMessage(clientSocket, str);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("receive :" + ex.Message);
                    if (myClientSocket.Connected)
                    {
                        myClientSocket.Shutdown(SocketShutdown.Both);
                        myClientSocket.Close();
                    }
                    break;
                }
            }
        }

        private static void SendMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            int totalsend = 0;
            while (true)
            {
                try
                {

                    for (int i = 0; i < 10; i++)
                    {
                        Thread.Sleep(1000);
                        string sendMessage = " client send Message Hellp-- " + i;
                        myClientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                        Console.WriteLine("send message to server:{0}", i);
                        totalsend++;
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine("send :" + ex.Message);
                    Console.WriteLine("total send count :" + totalsend);
                    if (myClientSocket.Connected)
                    {
                        myClientSocket.Shutdown(SocketShutdown.Both);
                        myClientSocket.Close();
                    }
                    break;
                }
            }
        }

        private static void ProcesMessage(object clientSocket, string str)
        {
            try
            {
                Socket myClientSocket = (Socket)clientSocket;
                //start command , set start flag true
                if (str == "START")
                {
                    startFlag = true;
                }
                else if (str == "HELLO")
                {
                    myClientSocket.Send(Encoding.ASCII.GetBytes("I am ok "));
                }
                else  // other command 
                {
                    //first test  the command exist or not
                    string cmd;
                    if (str.Contains(":"))
                    {
                        string[] inputcommands = str.Split(':');
                        cmd = inputcommands[0];
                    }
                    else { cmd = str; }

                    Type testType = Type.GetType("ClientRunner." + cmd);
                    if (testType != null)
                    {
                        //if exist, start a thread do the command
                        Thread docommand = new Thread(DoComand);
                        docommand.IsBackground = true;
                        ParameterOBJ pj = new ParameterOBJ();
                        pj.sc = myClientSocket;
                        pj.str = str;

                        docommand.Start(pj);
                    }
                    else //if command not exist, send error to control center
                    {
                        myClientSocket.Send(Encoding.ASCII.GetBytes("i don't know the command "));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("process mesage send :" + ex.Message);
            }
        }

        private static void DoComand(object pj)
        {
            string mystr;
            Socket sc =null;
            string str;
            try
            {
                //use Reflection get class instance 
                var mypj = (ParameterOBJ)pj;
                str = mypj.str;
                sc = mypj.sc;

                int testcount;
                if (str.Contains(":"))
                {
                    string[] inputcommands = str.Split(':');
                    mystr = inputcommands[0];
                    testcount = int.Parse(inputcommands[1]);
                }
                else 
                {
                    mystr = str;
                    //default test one time 
                    testcount = 1;
                }



                Type myType = Type.GetType("ClientRunner." + mystr);
                var obj = (ICommand)Activator.CreateInstance(myType);
                bool mybl = (bool)obj.Prepare(mystr,testcount);
                if (mybl)
                {
                    sc.Send(Encoding.ASCII.GetBytes("prepare is on "));
                }
                else
                {
                    sc.Send(Encoding.ASCII.GetBytes("prepare is failure,client close connect and exit "));
                    if (sc != null && sc.Connected)
                    {
                        sc.Shutdown(SocketShutdown.Both);
                        sc.Close();
                    }
                }
                //wait for start command
                while (true)
                {
                    Thread.Sleep(100);
                    if (startFlag)
                    {
                        Console.WriteLine("start flag is true");
                        break;
                    }
                }

                string  result = (string) obj.Do(mystr,sc,testcount);
                //send back the result 
                sc.Send(Encoding.ASCII.GetBytes(result));
            }
            catch (Exception ex)
            {
                //send response i don't know the command?
                Console.WriteLine("::do command exception {0}", ex.Message);
                if (sc != null && sc.Connected)
                {
                    sc.Shutdown(SocketShutdown.Both);
                    sc.Close();
                }
            }
        }
    }
}

  

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

namespace ClientRunner
{
    class ParameterOBJ
    {
        public Socket sc;
        public string str;
    }
}

  

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace ClientRunner
{
    public interface ICommand
    {
        //Object Do(Dictionary<string, Socket> socketDC, string message);
        Object Do(string message,Socket sc,int count);
        Object Prepare(string message,int count);
    }
}

  socket class :

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Text;

namespace Common.MySocket
{
    public class BaseSocket
    {
        byte[] buffer = new byte[1024];
        protected Socket _mysocket;
        protected IPAddress _ip;
        protected int _port;

        public BaseSocket(IPAddress ip, int port)
        {
            _ip = ip;
            _port = port;
        }

        public void SendMessage(Socket mysocket, string sendmessage)
        {
            try
            {
                if (mysocket.Connected)
                {
                    mysocket.Send(Encoding.ASCII.GetBytes(sendmessage));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("::{0}", ex.Message);
                if (mysocket.Connected)
                {
                    mysocket.Shutdown(SocketShutdown.Both);
                    mysocket.Close();
                }
                //let outside know what exception happen
                throw ex;
            }
        }

        public string RecvMessage(Socket mysocket)
        {
            try
            {
                if (mysocket.Connected)
                {
                    int receiveNumber = mysocket.Receive(buffer);
                    if (receiveNumber > 0)
                    {
                        String str = Encoding.ASCII.GetString(buffer, 0, receiveNumber);
                        Console.WriteLine("result:: receive response message::{0}", str);
                        return str;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("::{0}", ex.Message);
                if (mysocket.Connected)
                {
                    mysocket.Shutdown(SocketShutdown.Both);
                    mysocket.Close();
                }
                throw ex;
            }
            return null;
        }

        public void ClearBuffer()
        {
            Array.Clear(buffer, 0, buffer.Length);
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Common.MySocket
{
    public class ClientSocket : BaseSocket
    {
        public ClientSocket(IPAddress ip, int port) : base(ip, port)
        {
        }

        public bool Connect()
        {
            _mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                _mysocket.Connect(new IPEndPoint(_ip, _port));
                Console.WriteLine("sucess");
            }
            catch (Exception ex)
            {
                Console.WriteLine("failure! : {0}", ex.Message);
                return false;
            }
            return true;
        }
    }
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Common.MySocket
{
    public class ServerSocket : BaseSocket
    {
        public ServerSocket(IPAddress ip, int port) : base(ip, port)
        {
        }

        public void Init(int queueNum)
        {
            try
            {
                _mysocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _mysocket.Bind(new IPEndPoint(_ip, _port));
                _mysocket.Listen(queueNum);
                Console.WriteLine("start {0} success", _mysocket.LocalEndPoint.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Can't start socket connect {0}", ex.Message);
                throw ex;
            }
 
        }

        public Socket AcceptSocket()
        {
            return _mysocket.Accept();
        }
    }
}

  config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ServerIP" value="127.0.0.1"/>
    <add key="ServerPort" value="8888"/>
    <add key="QueueNum" value="5000"/>
    <add key ="Commands" value="Getx,GetxClear" />
  </appSettings>
   
</configuration>

  

 

转载于:https://www.cnblogs.com/cquccy/p/3252926.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值