Supersocket客户端服务端

服务端 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
namespace SuperSocketServer
{
    class Program
    {
        static AppServer appServer = null;
       static System.Threading.Thread thSend = null;
        static void Main(string[] args)
        {
             appServer = new AppServer();
             var    se = new SuperSocket.SocketBase.Config.ServerConfig();
            se.TextEncoding = "GB2312";
            se.Ip = "127.0.0.1";
            se.Port = 18083;  
            se.MaxRequestLength = 4096;
            se.SendBufferSize = 4096;

            thSend = new System.Threading.Thread(SendMsgToClient);
            thSend.Start();
            //Setup the appServer
            if (!appServer.Setup(se)) //Setup with listening port
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }
            Console.WriteLine();
            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }


            appServer.NewSessionConnected += appServer_NewSessionConnected;
            appServer.SessionClosed += appServer_SessionClosed;
            appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);

           // appServer.NewRequestReceived += appServer_NewRequestReceived;
            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }

            //Stop the appServer
            appServer.Stop();
            Console.WriteLine("The server was stopped!");
            Console.ReadKey();

        }
        static void appServer_NewRequestReceived(AppSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo)
        {
            Console.WriteLine("接收数据Boby:"+requestInfo.Body+ " !");
            Console.WriteLine("接收数据Key:" + requestInfo.Key + " !");
            switch (requestInfo.Key.ToUpper())
            {
                case ("ECHO"):
                    session.Send(requestInfo.Body);
                    break;
                case ("ADD"):
                    Console.WriteLine(" 向客户端发送数据");
                    session.Send(" 向客户端发送数据>>" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                    //session.Send(requestInfo.Parameters.Select(p => Convert.ToInt32(p)).Sum().ToString());
                    break;
                case ("MULT"):
                    var result = 1;
                    foreach (var factor in requestInfo.Parameters.Select(p => Convert.ToInt32(p)))
                    {
                        result *= factor;
                    }
                    session.Send(result.ToString());
                    break;
            }
            //throw new NotImplementedException();
        }


        static void appServer_SessionClosed(AppSession session, CloseReason value)
        {
            Console.WriteLine("Session:" + session.RemoteEndPoint + " SessionClosed");
            //throw new NotImplementedException();
            var temp = listSession.Find(f => f.SessionID == session.SessionID);
            if (temp != null)
            {
                listSession.Remove(temp);
            }
            //listSession.Add(session);
         
        }

        static List<AppSession> listSession = new List<AppSession>();
        static void appServer_NewSessionConnected(AppSession session)
        {
            Console.WriteLine("Session:" + session.RemoteEndPoint + " connect");
           //throw new NotImplementedException();

            listSession.Add(session);

        }

        static void SendMsgToClient()
        {

            while (true)
            {
                if (listSession.Count > 0)
                {
                    for (int i = 0; i < listSession.Count; i++)
                    {
                        listSession[i].Send(" 广播模式 > 发送消息到客户端 ");
                    }
                    System.Threading.Thread.Sleep(1000);
                }
                else
                {
                    System.Threading.Thread.Sleep(5000);
                }
            }

        }

      
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Windows.Forms;
using SuperSocket.ClientEngine;
using SuperSocket.ClientEngine.Protocol;
using System.Net.Sockets;
using SuperSocket.SocketBase;

namespace SuperSocketClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            TcpServerConnection();
        }
  
        AsyncTcpSession client = null;

        void TcpServerConnection()
        {
            if (client != null)
                client.Close();
            client = null;
            client = new AsyncTcpSession();
            client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 18083));
            // 连接断开事件
            client.Closed += client_Closed;
            // 收到服务器数据事件
            client.DataReceived += client_DataReceived;
            // 连接到服务器事件
            client.Connected += client_Connected;
            // 发生错误的处理
            client.Error += client_Error;

        }
        void client_Error(object sender, ErrorEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
        }

        void client_Connected(object sender, EventArgs e)
        {
            MessageBox.Show("连接成功");
        }

        void client_DataReceived(object sender, DataEventArgs e)
        {
            string msg = Encoding.Default.GetString(e.Data,0,e.Length).ToString().Replace("\r\n","");
            Console.WriteLine(msg);
        }

        void client_Closed(object sender, EventArgs e)
        {
            MessageBox.Show("连接断开");
        }


        /// <summary>
        /// 向服务器发命令行协议的数据
        /// </summary>
        /// <param name="key">命令名称</param>
        /// <param name="data">数据</param>
        public void SendCommand(string key, string data)
        {
            if (client.IsConnected)
            {
                byte[] arr = Encoding.Default.GetBytes(string.Format("{0} {1}", key, data + "\r\n"));
                client.Send(arr, 0, arr.Length);
            }
            else
            {
                MessageBox.Show ("未建立连接");
                //throw new InvalidOperationException("未建立连接");
                TcpServerConnection();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SendCommand("ADD", textBox1.Text);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40098572/article/details/100089420
今日推荐