SharpNetty Tutorial

本文提供了一个基于SharpNetty库的基本客户端/服务器解决方案教程。包括下载库、添加引用到C#项目、修改代码实现登录、消息传递等功能。详细解释了每个步骤并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



This is a very basic tutorial (comment based) that will allow you to create a basic client/server solution with my networking library: SharpNetty.

 

Your end result should look something like this:

NyKeehY.png

 

 

 

 

 

Download the latest SharpNetty binary from: http://rpgdevs.com/sharpnetty/

 

After you have downloaded that, we need to add the library reference to our C# projects. If you do not know how to create/add library references to your project, I would recommend searching Youtube for some basic C# tutorials.

 

 

After you have done that, you replace your Program.cs code with this:

 

Please make sure to go through the code and read everything. I make sure to explain any vital features that you will need to thoroughly understand in order to properly use my Networking library. 

using SharpNetty;
using System;
using System.Collections.Generic;
using System.Net;

namespace Server
{
    public class Program
    {
        public class LoginPacket : Packet
        {
            private void WriteData(bool loginOkay)
            {
                // Flush the byte-array storing this packet's unique information.
                this.DataBuffer.Flush();

                // Write a boolean that signifies the login going a-okay.
                this.DataBuffer.WriteBool(loginOkay);
            }

            public override void Execute(Netty netty)
            {
                // Get their requested username,
                string username = this.DataBuffer.ReadString();

                // Set their username.
                Program.Server.clients[this.SocketIndex].UserName = username;

                // Write to this packet telling the client that all was fine logging in.
                this.WriteData(true);

                // Send this packet back to the client.
                Program.Server.clients[this.SocketIndex].SendPacket(this);
            }

            public override int PacketID
            {
                // Just an identification number for this packet.
                get { return 0; }
            }
        }

        public class MessagePacket : Packet
        {
            private void WriteData(string message)
            {
                // Flush the byte-array storing this packet's unique information.
                this.DataBuffer.Flush();

                // Write the desired message to the byte-array.
                this.DataBuffer.WriteString(message);
            }

            public override void Execute(Netty netty)
            {
                // Get the * message that's so dire from the client.
                string message = Program.Server.clients[this.SocketIndex].UserName + " says " + this.DataBuffer.ReadString();

                // Write the message back to this packet's byte array (we're reusing this packet).
                this.WriteData(message);

                // This might seem a little strange for any newcomers to C#. We're basically telling the RTE to cast netty (an instance of an abstract class that both NettyServer & NettyClient implement) to NettyServer.
                NettyServer nettyServer = netty as NettyServer;

                // Send the message to every current connection.
                nettyServer.BroadcastPacket(this);
            }

            public override int PacketID
            {
                // Just an identification number for this packet.
                get { return 1; }
            }
        }

        public class Client
        {
            // Stores this client's connection information.
            private NettyServer.Connection _connection;

            // Property that gets/sets this client's username.
            public string UserName { get; set; }

            // Property that gets/sets this client's ip address.
            public string IP { get; private set; }

            public Client(NettyServer.Connection connection)
            {
                _connection = connection;
                this.IP = _connection.Socket.RemoteEndPoint.ToString();
            }

            // Method Send a packet to this client.
            public void SendPacket(Packet packet)
            {
                _connection.SendPacket(packet);
            }
        }

        private NettyServer nettyServer;

        // Stores our active connections.
        private Dictionary<int, Client> clients;

        public Program()
        {
            // IP that we're going to listen on.
            string ip = "127.0.0.1";
            // Port that we're going to listen on.
            int port = 4000;

            // Create a new instance of the Dictionary Class using an integer for identification and a Client class for our storage.
            this.clients = new Dictionary<int, Client>();

            // Create a new instance of NettyServer.
            this.nettyServer = new NettyServer(true);

            // Bind the socket to our ip & port.
            nettyServer.BindSocket(ip, port);

            // Direct the NewConnection and LostConnection delegate to their proper handlers.
            nettyServer.Handle_NewConnection = this.Handle_NewConnection;
            nettyServer.Handle_LostConnection = this.Handle_LostConnection;

            // Listen for any incoming connections.
            nettyServer.Listen();
        }

        private void Handle_NewConnection(int socketIndex)
        {
            // Add a new client with the connection information to our dictionary.
            this.clients.Add(socketIndex, new Client(this.nettyServer.GetConnection(socketIndex)));
        }

        private void Handle_LostConnection(int socketIndex)
        {
            Console.WriteLine("Lost connection with " + this.clients[socketIndex].IP);

            // Remove the client from our dictionary.
            this.clients.Remove(socketIndex);
        }

        public static Program Server;

        private static void Main(string[] args)
        {
            Program.Server = new Program();
        }
    }
}

After you have done that, add the following code to another project (replace Program.cs as you did with the Server):

using SharpNetty;
using System;
using System.Threading;

namespace Client
{
    public class Program
    {
        public class LoginPacket : Packet
        {
            public void WriteData(string username)
            {
                // Write our username to the databuffer (byte-array containing information about this packet).
                this.DataBuffer.WriteString(username);
            }

            public override void Execute(Netty netty)
            {
                // Was our login successful? If so, we better * let ourselves know!
                bool success = this.DataBuffer.ReadBool();

                if (success)
                {
                    Program.Client.Login();
                }
            }

            public override int PacketID
            {
                // Just a stupid means of identifying the packet. We need this to be consistent on both ends.
                get { return 0; }
            }
        }

        public class MessagePacket : Packet
        {
            public void WriteData(string message)
            {
                // Write our message to the databuffer (byte-array containing information about this packet).
                this.DataBuffer.WriteString(message);
            }

            public override void Execute(Netty netty)
            {
                // Get the * message from the server and print that *!
                Console.WriteLine(">> " + this.DataBuffer.ReadString());
            }

            public override int PacketID
            {
                // Just a stupid means of identifying the packet. We need this to be consistent on both ends.
                get { return 1; }
            }
        }

        public static Program Client;

        private NettyClient nettyClient;

        public Program()
        {
            // Create a new instance of the class NettyClient.
            this.nettyClient = new NettyClient(true);

            // Direct the Handle_ConnectionLost delegate to our local method.
            this.nettyClient.Handle_ConnectionLost = this.Handle_ConnectionLost;

            // Get the server ip.
            Console.Write("Server IP: ");
            string serverIP = Console.ReadLine();

            // Get the server port.
            Console.Write("Server Port: ");
            int serverPort = int.Parse(Console.ReadLine());

            // Attempt to connect to the server 1 time. Store the connection status in a variable named connected.
            bool connected = this.nettyClient.Connect(serverIP, serverPort, 1);

            // If the connection was successful, send a login-packet.
            if (connected)
            {
                // Get this client's username.
                Console.Write("Username: ");
                string userName = Console.ReadLine();

                // Create a new instance of the LoginPacket class.
                LoginPacket loginPacket = new LoginPacket();
                // Write data to the packet (our username).
                loginPacket.WriteData(userName);
                // Send the packet to the server.
                nettyClient.SendPacket(loginPacket);
            }
            else
            {
                // We failed to connect... terminate the client.
                Console.WriteLine("Failed to connect!");
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                Environment.Exit(0);
            }
        }

        private void Handle_ConnectionLost()
        {
            // We lost our connection... terminate the client.
            Console.WriteLine("Connection terminated... shutting down");
            Environment.Exit(0);
        }

        public void Login()
        {
            MessagePacket messagePacket;

            // Create a new thread for client input.
            // This frees up writing to the console.
            new Thread(() =>
            {
                // Create an input loop to wait for messages.
                while (true)
                {
                    // Get a message to send.
                    string message = Console.ReadLine();
                    // Create a new instance of the MessagePacket class.
                    messagePacket = new MessagePacket();
                    // Write data to the packet (our message).
                    messagePacket.WriteData(message);
                    // Send the packet to the server.
                    nettyClient.SendPacket(messagePacket);
                }
            }).Start();
        }

        private static void Main(string[] args)
        {
            Program.Client = new Program();
        }
    }
}

After you have done that, you should be good to go! Once again, make sure to go through the comments and read everything.

 

If you don't understand something, feel free to leave a post below!

 

Shortcut:

Spoiler
If you're too lazy to add in the code manually, you can download the project here: http://www.rpgdevs.c...ttyTutorial.zip

 

Regards,

John Lamontagne

标题基于SpringBoot+Vue的社区便民服务平台研究AI更换标题第1章引言介绍社区便民服务平台的研究背景、意义,以及基于SpringBoot+Vue技术的研究现状和创新点。1.1研究背景与意义分析社区便民服务的重要性,以及SpringBoot+Vue技术在平台建设中的优势。1.2国内外研究现状概述国内外在社区便民服务平台方面的发展现状。1.3研究方法与创新点阐述本文采用的研究方法和在SpringBoot+Vue技术应用上的创新之处。第2章相关理论介绍SpringBoot和Vue的相关理论基础,以及它们在社区便民服务平台中的应用。2.1SpringBoot技术概述解释SpringBoot的基本概念、特点及其在便民服务平台中的应用价值。2.2Vue技术概述阐述Vue的核心思想、技术特性及其在前端界面开发中的优势。2.3SpringBoot与Vue的整合应用探讨SpringBoot与Vue如何有效整合,以提升社区便民服务平台的性能。第3章平台需求分析与设计分析社区便民服务平台的需求,并基于SpringBoot+Vue技术进行平台设计。3.1需求分析明确平台需满足的功能需求和性能需求。3.2架构设计设计平台的整体架构,包括前后端分离、模块化设计等思想。3.3数据库设计根据平台需求设计合理的数据库结构,包括数据表、字段等。第4章平台实现与关键技术详细阐述基于SpringBoot+Vue的社区便民服务平台的实现过程及关键技术。4.1后端服务实现使用SpringBoot实现后端服务,包括用户管理、服务管理等核心功能。4.2前端界面实现采用Vue技术实现前端界面,提供友好的用户交互体验。4.3前后端交互技术探讨前后端数据交互的方式,如RESTful API、WebSocket等。第5章平台测试与优化对实现的社区便民服务平台进行全面测试,并针对问题进行优化。5.1测试环境与工具介绍测试
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值