Working with Mongo Wire Protocol on C#

Posted by – August 2, 2009

Last saturday I started a small C# project when I try to send a message to MongoDB, after few hours working on it I finally could see the database receiving the message sucessfully.

Here’s the code that I used to send the message to database:

Program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace Mongo.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            //Creating a socket connection to mongodb instance
            Socket socket = new Socket(AddressFamily.InterNetwork,
                  SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(Dns.GetHostAddresses("192.168.0.103"), 27017);

            //This is the message to be sent to mongodb instance
            List<byte> message = new List<byte>();
            message.AddRange(Encoding.UTF8.GetBytes("This is a test."));
            message.Add(0x00);

            //Each message to be sent to mongodb must have a header like
            //where we can specify which operation will be performed on server.
            List<byte> header = new List<byte>();
            header.AddRange(BitConverter.GetBytes(16 + message.Count));
            header.AddRange(BitConverter.GetBytes(1));
            header.AddRange(BitConverter.GetBytes(0));
            header.AddRange(BitConverter.GetBytes(1000));

            //Now we must put the message header a body together before send it
            // to the server.
            List<ArraySegment<byte>> buffer = new List<ArraySegment<byte>>();
            buffer.Add(new ArraySegment<byte>(header.ToArray()));
            buffer.Add(new ArraySegment<byte>(message.ToArray()));

            //Send the message to the server
            socket.Send(buffer);

            //Close connection
            socket.Close();
        }
    }

A very good documentation about how to write a MongoDB driver can be found here.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>