SuperSocket框架实现服务器和Winform客户端

服务器:服务器使用的是控制台程序。
界面:

代码:
需要使用NuGet管理工具添加SuperSocket和SuperSocket.SocketEngine的引用才能生效

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 SuperSocketServerConsoleAppDemo1
{
    class Program
    {
        /// <summary>
        /// 定义一个Socket服务
        /// </summary>
        static AppServer appServer = null;
        /// <summary>
        /// 定义一个线程
        /// </summary>
        static System.Threading.Thread thSend = null;

        static List<AppSession> listSession = new List<AppSession>();
        static void Main(string[] args)
        {
            appServer = new AppServer();
            var se = new SuperSocket.SocketBase.Config.ServerConfig();
            se.TextEncoding = "UTF-8";
            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(安装AppServer)
            if (!appServer.Setup(se)) //Setup with listening port
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }
            Console.WriteLine();
            //Try to start the appServer(尝试启动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();
        }
        /// <summary>
        /// 在收到完整请求项时发生。
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        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();
        }
        /// <summary>
        /// 获取/设置会话关闭事件处理程序。
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        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);
        }
        /// <summary>
        /// 新会话连接后将执行的操作
        /// </summary>
        /// <param name="session"></param>
        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);
                }
            }
        }
    }
}


客户端:客户端使用的是一个winform程序。
界面:发生数据库的数据,将数据发送到服务器。


代码:
界面代码有系统生成,添加一个按钮和输入框。

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

namespace SuperSocketClientWindowsFormsAppDemo1
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 异步的客户端连接套接字
        /// </summary>
        AsyncTcpSession client = null;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TcpServerConnection();
        }
        void TcpServerConnection() 
        {
            try
            {
                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;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
        }
        /// <summary>
        /// 发生错误的处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_Error(object sender, ErrorEventArgs e)
        {
            //MessageBox.Show(e.Exception.Message);
            Console.WriteLine(e.Exception.Message);
        }
        /// <summary>
        /// 连接断开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_Connected(object sender, EventArgs e)
        {
            MessageBox.Show("连接成功");
        }
        /// <summary>
        /// 收到服务器数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DataReceived(object sender, DataEventArgs e)
        {
            string msg = Encoding.UTF8.GetString(e.Data, 0, e.Length).ToString().Replace("\r\n", "");
            Console.WriteLine(msg);
        }
        /// <summary>
        /// 连接断开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_Closed(object sender, EventArgs e)
        {
            Console.WriteLine("连接断开");
            while (client == null || !client.IsConnected)
            {
                TcpServerConnection();
                System.Threading.Thread.Sleep(3000);
            }
        }
        /// <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);
        }
    }
}


此代码支持断开重连。

项目源码:https://download.csdn.net/download/xwwwill/85125204

PS:
SuperSocket框架实现服务器和Winform客户端_supersocket winform 服务端 群发-CSDN博客

SuperSocket 1.6 中文文档

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值