メールスロット Mailslot(受信)

詳細は省略します。
メールスロット経由でデータを受信するサンプルです。

タイマーを使って
一定周期でメールスロットに溜まったデータを取得しています。
応用すればデバッグトレースなどに役立つと思います。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.IO;

namespace MailSlotSample
{
    public partial class FormMain : Form
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
            static extern SafeFileHandle CreateMailslot(
            string lpName,
            uint nMaxMessageSize,
            uint lReadTimeout,
            IntPtr lpSecurityAttributes);

        [DllImport("kernel32.dll")]
            static extern bool GetMailslotInfo(
            SafeFileHandle hMailslot,
            ref uint lpMaxMessageSize,
            ref uint lpNextSize,
            ref uint lpMessageCount,
            ref uint lpReadTimeout);

        [DllImport("kernel32.dll", SetLastError = true)]
            static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
            uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
            uint dwFlagsAndAttributes, IntPtr hTemplateFile);

        public const uint FILE_ATTRIBUTE_NORMAL = 0x80;
        public const short INVALID_HANDLE_VALUE = -1;
        public const uint GENERIC_READ = 0x80000000;
        public const uint GENERIC_WRITE = 0x40000000;
        public const uint CREATE_NEW = 1;
        public const uint CREATE_ALWAYS = 2;
        public const uint OPEN_EXISTING = 3;
        public const uint FILE_SHARE_READ = 0x00000001;

        private enum MailSlotStatus : uint
        {
            MAILSLOT_NO_MESSAGE = 0xffffffff,
        }

        const string MAILSLOT_NAME = "\\\\.\\mailslot\\hogehoge";

        //
        // メールスロットハンドル
        //
        SafeFileHandle _handleMailslot = null;

        //
        // メールスロットから情報取得するためのStream
        //
        FileStream _fs = null;

        public FormMain()
        {
            InitializeComponent();

            // メールスロットハンドル生成
            _handleMailslot = CreateMailslot(MAILSLOT_NAME, 0, 0, (IntPtr)0);

            // メールスロットから情報取得するためのStream
            _fs = new FileStream(_handleMailslot, FileAccess.Read);

            // タイマー始動
            timer.Enabled = true;
        }

        ~FormMain()
        {
            _fs.Close();
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            //
            // タイマーを使って一定間隔でメールスロットからRead
            //
            string text = ReadMailSlot(MAILSLOT_NAME, 4096);

            // ここで取得したtextを表示。TextBoxやListBoxに追加するとかお好きにどうぞ
            MessageBox.Show(text);
        }

        private string ReadMailSlot(string slot, uint bufSize)
        {
            string ret = string.Empty;
            try
            {
                if (_handleMailslot.IsInvalid)
                    return ret;

                uint maxMessageSize = 1;
                uint nextSize = 0;
                uint messageCount = 0;
                uint readTimeout = 0;

                GetMailslotInfo(_handleMailslot, ref maxMessageSize, ref nextSize, ref messageCount, ref readTimeout);

                if (messageCount > 0 && nextSize != (uint)MailSlotStatus.MAILSLOT_NO_MESSAGE)
                {
                    byte[] buf = new byte[bufSize];
                    int len = _fs.Read(buf, 0, buf.Length);

                    // 適時、文字コードは送信元に合わせてください
                    ret = Encoding.Unicode.GetString(buf, 0, len);
                }
            }
            catch (Exception ex)
            {
                // 何かエラーだって!
                MessageBox.Show(ex.Message);
            }

            return ret;
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)