簡體   English   中英

在C#/ Win8中的StreamSocket上等待消息

[英]Waiting for messages on a StreamSocket in C#/Win8

我正在嘗試作為輔助項目在Windows 8中構建IRC客戶端,作為學習網絡編程的一種方式。 但是,我找不到構造偵聽器的最佳方法。

我有一個創建StreamSocket並連接到服務器的類。 現在我需要讓我的類偵聽來自服務器收到的消息,並在消息傳入回調委托。據我所知,StreamSocket只給我一個方法來拉任何當前等待的插座,但沒有對傳入消息的某種回調。 做這個的最好方式是什么?

我想您將把它實現為Windows服務,因此您的代碼看起來很像下面的代碼。 其中大部分是基礎架構,可讓您輕松調試服務。 我知道這會污染示例,但沒有它會做太多工作。

服務實現是在庫中而不是直接在服務主機中,因為我經常編寫通過WCF發布接口的服務,而總是可以將主機與服務分開就不那么麻煩了。

服務主機

using IrcServiceLibrary;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading;
using System.Xml;

namespace IrcServiceHost
{
  internal static class Program
  {
    /// <summary>
    /// Launches as an application when an argument "app" is supplied.
    /// Otherwise launches as a Windows Service.
    /// </summary>
    private static void Main(string[] arg)
    {
      var args = new List<string>(arg);
      ServiceBase[] ServicesToRun = new ServiceBase[]
      {
        new IrcServiceLibrary.Irc(
            Properties.Settings.Default.IrcTcpPort)
          };
      if (args.Contains("app"))
      {
        foreach (IExecutableService es in ServicesToRun)
          es.StartService();
        Thread.Sleep(Timeout.Infinite);
      }
      else
      {
        ServiceBase.Run(ServicesToRun);
      }
    }
  }
}

會議建立

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceProcess;
using System.Threading;

namespace IrcServiceLibrary
{
  /// <summary>
  /// Listens for TCP connection establishment and creates an 
  /// IrcSession object to handle the test session.
  /// </summary>
  [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
  public partial class Irc : ServiceBase, IExecutableService
  {
    AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
    TcpListener _tcpListener;
    List<IrcSession> _sessions = new List<IrcSession>();

    /// <summary>
    /// Creates Irc and applies configuration supplied by the service host.
    /// </summary>
    /// <param name="tcpPort">Port on which the session is established.</param>
    public Irc(int tcpPort)
    {
      Trace.TraceInformation("NetReady service created {0}", GetHashCode());
      InitializeComponent();
      _tcpListener = new TcpListener(IPAddress.Any, tcpPort); 
      NetReadySession.Sessions = _sessions;
    }

    void AcceptTcpClient(IAsyncResult asyncResult)
    {
      var listener = asyncResult.AsyncState as TcpListener;
      var tcpClient = listener.EndAcceptTcpClient(asyncResult);
      try
      {
        new NetReadySession(tcpClient);
      }
      catch (IndexOutOfRangeException)
      {
        //no free session - NetReadySession ctor already informed client, no action here
      } 
      _tcpListener.BeginAcceptTcpClient(AcceptTcpClient, _tcpListener);
    }

    /// <summary>
    /// <see cref="StartService">ServiceStart</see> 
    /// </summary>
    /// <param name="args">Arguments passed by the service control manager</param>
    protected override void OnStart(string[] args)
    {
      StartService();
    }

    /// <summary>
    /// <see cref="StopService">ServiceStop</see> 
    /// </summary>
    protected override void OnStop()
    {
      StopService();
    }

    void Execute(object state)
    {
      Trace.TraceInformation("IRC service started");
      _tcpListener.Start();
      _tcpListener.BeginAcceptTcpClient(AcceptTcpClient, _tcpListener);
      _autoResetEvent.WaitOne();
      _tcpListener.Stop();
    }

    internal static int UdpPortLow { get; set; }

    internal static int UdpPortHigh { get; set; }

    /// <summary>
    /// Starts the service. OnStart uses this method to implement startup behaviour.
    /// This guarantees identical behaviour across application and service modes.
    /// </summary>
    public void StartService()
    {
      ThreadPool.QueueUserWorkItem(Execute);
    }

    /// <summary>
    /// Stops the service. OnStop uses this method to implement shutdown behaviour.
    /// This guarantees identical behaviour across application and service modes.
    /// </summary>
    public void StopService()
    {
      _autoResetEvent.Set();
    }
  }
}

會話行為

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace IrcServiceLibrary
{
  public class IrcSession
  {    
    /// <summary>
    /// Exists to anchor sessions to prevent premature garbage collection
    /// </summary>
    public static List<IrcSession> Sessions;
    TcpClient _tcpClient;
    NetworkStream _stream;
    byte[] _buf; //remain in scope while awaiting data

    /// <summary>
    /// Created dynamically to manage an Irc session. 
    /// </summary>
    /// <param name="tcpClient">The local end of the TCP connection established by a test client 
    /// to request and administer a test session.</param>
    public IrcSession(TcpClient tcpClient)
    {
      Sessions.Add(this);
      _tcpClient = tcpClient;
      _stream = _tcpClient.GetStream();
      _buf = new byte[1];
      _stream.BeginRead(_buf, 0, 1, IncomingByteHandler, _buf);
    }

    void IncomingByteHandler(IAsyncResult ar)
    {
      byte[] buf = ar.AsyncState as byte[];
      try
      {
        byte[] buf = ar.AsyncState as byte[];
        int cbRead = _stream.EndRead(ar);
        //do something with the incoming byte which is in buf
        //probably feed it to a state machine
      }
      finally
      {
        //restart listening AFTER digesting byte to ensure in-order delivery to this code
        _stream.BeginRead(buf, 0, 1, IncomingByteHandler, buf);
      }
    }

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM