Example Server

You can download the full project here. This server starts up on port 25565 and outputs the server chat to the console. Note that this server is more complex than need be, you can make a much more simple one that does not save the world or handle chat.

Code (C#): Example Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibMinecraft.Model;
using LibMinecraft.Server;
using System.IO;

namespace ServerExample
{
    class Program
    {
        static MultiplayerServer server;

        static void Main(string[] args)
        {
            // Represents details about a Minecraft server
            MinecraftServer mServer = new MinecraftServer();
            mServer.Port = 25565;
            mServer.MotD = "Welcome to LibMinecraft!";

            // Runs all server logic, including block updates,
            // networking, world storage, etc
            server = new MultiplayerServer(mServer);

            // Worlds are Minecraft worlds that host blocks and entities.
            World world = new World();
            if (Directory.Exists("world"))
                world.LoadFromBinary("world");
            else
                world.SaveToBinary("world");
            // The binary format is LibMinecraft-specific

            server.AddWorld(world);
            // LibMinecraft saves the world every 5 seconds by default.
            // You can change this with server.SaveFrequency

            // You need to handle these events if you want messages to show up
            // in the chat about them.
            server.OnPlayerJoin +=
                          new EventHandler<PlayerEventArgs>(server_OnPlayerJoin);
            server.OnPlayerLeave +=
                          new EventHandler<PlayerEventArgs>(server_OnPlayerLeave);
            server.OnChat +=
                          new EventHandler<ChatEventArgs>(server_OnChat);

            server.Start();

            while (Console.ReadKey(true).Key != ConsoleKey.Q) ;
            // Press Q to stop the server and quit

            server.Stop(); // Not strictly required, but nice to have

            world.Save();
        }

        static void server_OnChat(object sender, ChatEventArgs e)
        {
            Console.WriteLine(e.RawText);
        }

        static void server_OnPlayerLeave(object sender, PlayerEventArgs e)
        {
            server.SendChat(e.Player.PlayerEntity.Name + " has left the game.");
            Console.WriteLine(e.Player.PlayerEntity.Name + " has left the game.");
        }

        static void server_OnPlayerJoin(object sender, PlayerEventArgs e)
        {
            server.SendChat(e.Player.PlayerEntity.Name + " has joined the game.");
            Console.WriteLine(e.Player.PlayerEntity.Name + " has joined the game.");
        }
    }
}

Last edited Feb 24, 2012 at 10:22 PM by sircmpwn, version 7

Comments

No comments yet.