Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

SharpNetty Tutorial.


JohnPony
 Share

Recommended Posts

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:

![](http://i.imgur.com/NyKeehY.png)

Download the latest SharpNetty binary from: [http://rpgdevs.com/sharpnetty/](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 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();

// 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:

>! If you're too lazy to add in the code manually, you can download the project here: [http://www.rpgdevs.com/sharpnetty/SharpNettyTutorial.zip](http://www.rpgdevs.com/sharpnetty/SharpNettyTutorial.zip)

Regards,

John Lamontagne
Link to comment
Share on other sites

  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...