【问题标题】:TCPIP networking with C#使用 C# 的 TCPIP 网络
【发布时间】:2010-01-24 17:13:59
【问题描述】:

大家好,

我将编写一些代码来监听来自 GSM 手机通过 GPRS 的 TCPIP 消息。在充足的时间里,我认为这是在虚拟专用服务器上运行的,它很可能每秒处理多条消息。

我是一个网络编程的处女,所以我在互联网上做了一些研究,并阅读了一些教程。我目前正在考虑的方法是使用套接字来监视端口的 Windows 服务。如果我的理解是正确的,我需要一个套接字来侦听来自客户端的连接,并且每次有人尝试连接该端口时,我都会通过另一个套接字与他们进行通信?这听起来对更有经验的人来说是正确的吗?

我计划使用异步通信,但更大的设计问题是是否使用线程。线程不是我真正玩过的东西,而且我知道一些陷阱 - 竞争条件和调试问题只是两个。

如果我避免使用线程,我知道我必须提供一个对象来充当特定对话的标识符。我正在为此考虑 GUID - 有什么意见吗?

提前感谢您的任何回复...

马丁

【问题讨论】:

  • 您可能需要线程(或线程池)来处理来自客户端的请求。至少,这是我在使用服务发现时的经验。
  • 不,我们没有。从基于 IO 完成端口的 .net framework 2.0 SP1 套接字实现开始。而且这种方法比对一个传入连接使用一个线程更有效。我们不需要事件线程池。 (有关更多信息,请参阅我的回答)。

标签: c# networking tcp


【解决方案1】:

从 .net framework 2.0 SP1 开始,与异步套接字相关的套接字库发生了一些变化。

在后台使用的所有多线程。我们不需要手动使用多线程(我们甚至不需要显式使用 ThreadPool)。我们所做的一切——使用BeginAcceptSocket 开始接受新连接,并在接受新连接后使用SocketAsyncEventArgs

简短的实现:

//In constructor or in method Start
var tcpServer = new TcpListener(IPAddress.Any, port);
tcpServer.Start();
tcpServer.BeginAcceptSocket(EndAcceptSocket, tcpServer);

//In EndAcceptSocket
Socket sock= lister.EndAcceptSocket(asyncResult);
var e = new SocketAsyncEventArgs();
e.Completed += ReceiveCompleted; //some data receive handle
e.SetBuffer(new byte[SocketBufferSize], 0, SocketBufferSize);
if (!sock.ReceiveAsync(e))
{//IO operation finished syncronously
  //handle received data
  ReceiveCompleted(sock, e);
}//IO operation finished syncronously
//Add sock to internal storage

全面实施:

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

namespace Ample
{
    public class IPEndPointEventArgs : EventArgs
    {
        public IPEndPointEventArgs(IPEndPoint ipEndPoint)
        {
            IPEndPoint = ipEndPoint;
        }

        public IPEndPoint IPEndPoint { get; private set; }
    }

    public class DataReceivedEventArgs : EventArgs
    {
        public DataReceivedEventArgs(byte[] data, IPEndPoint ipEndPoint)
        {
            Data = data;
            IPEndPoint = ipEndPoint;
        }

        public byte[] Data { get; private set; }
        public IPEndPoint IPEndPoint { get; private set; }

    }
    /// <summary>
    /// TcpListner wrapper
    /// Encapsulates asyncronous communications using TCP/IP.
    /// </summary>
    public sealed class TcpServer : IDisposable
    {
        //----------------------------------------------------------------------
        //Construction, Destruction
        //----------------------------------------------------------------------
        /// <summary>
        /// Creating server socket
        /// </summary>
        /// <param name="port">Server port number</param>
        public TcpServer(int port)
        {
            connectedSockets = new Dictionary<IPEndPoint, Socket>();
            tcpServer = new TcpListener(IPAddress.Any, port);
            tcpServer.Start();
            tcpServer.BeginAcceptSocket(EndAcceptSocket, tcpServer);
        }
        ~TcpServer()
        {
            DisposeImpl(false);
        }
        public void Dispose()
        {
            DisposeImpl(true);
        }

        //----------------------------------------------------------------------
        //Public Methods
        //----------------------------------------------------------------------

        public void SendData(byte[] data, IPEndPoint endPoint)
        {
            Socket sock;
            lock (syncHandle)
            {
                if (!connectedSockets.ContainsKey(endPoint))
                    return;
                sock = connectedSockets[endPoint];
            }
            sock.Send(data);
        }

        //----------------------------------------------------------------------
        //Events
        //----------------------------------------------------------------------
        public event EventHandler<IPEndPointEventArgs> SocketConnected;
        public event EventHandler<IPEndPointEventArgs> SocketDisconnected;
        public event EventHandler<DataReceivedEventArgs> DataReceived;

        //----------------------------------------------------------------------
        //Private Functions
        //----------------------------------------------------------------------
        #region Private Functions
        //Обработка нового соединения
        private void Connected(Socket socket)
        {
            var endPoint = (IPEndPoint)socket.RemoteEndPoint;

            lock (connectedSocketsSyncHandle)
            {
                if (connectedSockets.ContainsKey(endPoint))
                {
                    theLog.Log.DebugFormat("TcpServer.Connected: Socket already connected! Removing from local storage! EndPoint: {0}", endPoint);
                    connectedSockets[endPoint].Close();
                }

                SetDesiredKeepAlive(socket);
                connectedSockets[endPoint] = socket;
            }

            OnSocketConnected(endPoint);
        }

        private static void SetDesiredKeepAlive(Socket socket)
        {
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            const uint time = 10000;
            const uint interval = 20000;
            SetKeepAlive(socket, true, time, interval);
        }
        static void SetKeepAlive(Socket s, bool on, uint time, uint interval)
        {
            /* the native structure
            struct tcp_keepalive {
            ULONG onoff;
            ULONG keepalivetime;
            ULONG keepaliveinterval;
            };
            */

            // marshal the equivalent of the native structure into a byte array
            uint dummy = 0;
            var inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
            BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
            BitConverter.GetBytes((uint)time).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
            BitConverter.GetBytes((uint)interval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
            // of course there are other ways to marshal up this byte array, this is just one way

            // call WSAIoctl via IOControl
            int ignore = s.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);

        }
        //socket disconnected handler
        private void Disconnect(Socket socket)
        {
            var endPoint = (IPEndPoint)socket.RemoteEndPoint;

            lock (connectedSocketsSyncHandle)
            {
                connectedSockets.Remove(endPoint);
            }

            socket.Close();

            OnSocketDisconnected(endPoint);
        }

        private void ReceiveData(byte[] data, IPEndPoint endPoint)
        {
            OnDataReceived(data, endPoint);
        }

        private void EndAcceptSocket(IAsyncResult asyncResult)
        {
            var lister = (TcpListener)asyncResult.AsyncState;
            theLog.Log.Debug("TcpServer.EndAcceptSocket");
            if (disposed)
            {
                theLog.Log.Debug("TcpServer.EndAcceptSocket: tcp server already disposed!");
                return;
            }

            try
            {
                Socket sock;
                try
                {
                    sock = lister.EndAcceptSocket(asyncResult);
                    theLog.Log.DebugFormat("TcpServer.EndAcceptSocket: remote end point: {0}", sock.RemoteEndPoint);
                    Connected(sock);
                }
                finally
                {
                    //EndAcceptSocket can failes, but in any case we want to accept 
new connections
                    lister.BeginAcceptSocket(EndAcceptSocket, lister);
                }

                //we can use this only from .net framework 2.0 SP1 and higher
                var e = new SocketAsyncEventArgs();
                e.Completed += ReceiveCompleted;
                e.SetBuffer(new byte[SocketBufferSize], 0, SocketBufferSize);
                BeginReceiveAsync(sock, e);

            }
            catch (SocketException ex)
            {
                theLog.Log.Error("TcpServer.EndAcceptSocket: failes!", ex);
            }
            catch (Exception ex)
            {
                theLog.Log.Error("TcpServer.EndAcceptSocket: failes!", ex);
            }
        }

        private void BeginReceiveAsync(Socket sock, SocketAsyncEventArgs e)
        {
            if (!sock.ReceiveAsync(e))
            {//IO operation finished syncronously
                //handle received data
                ReceiveCompleted(sock, e);
            }//IO operation finished syncronously
        }

        void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            var sock = (Socket)sender;
            if (!sock.Connected)
                Disconnect(sock);
            try
            {

                int size = e.BytesTransferred;
                if (size == 0)
                {
                    //this implementation based on IO Completion ports, and in this case
                    //receiving zero bytes mean socket disconnection
                    Disconnect(sock);
                }
                else
                {
                    var buf = new byte[size];
                    Array.Copy(e.Buffer, buf, size);
                    ReceiveData(buf, (IPEndPoint)sock.RemoteEndPoint);
                    BeginReceiveAsync(sock, e);
                }
            }
            catch (SocketException ex)
            {
                //We can't truly handle this excpetion here, but unhandled
                //exception caused process termination.
                //You can add new event to notify observer
                theLog.Log.Error("TcpServer: receive data error!", ex);
            }
            catch (Exception ex)
            {
                theLog.Log.Error("TcpServer: receive data error!", ex);
            }
        }

        private void DisposeImpl(bool manualDispose)
        {
            if (manualDispose)
            {
                //We should manually close all connected sockets
                Exception error = null;
                try
                {
                    if (tcpServer != null)
                    {
                        disposed = true;
                        tcpServer.Stop();
                    }
                }
                catch (Exception ex)
                {
                    theLog.Log.Error("TcpServer: tcpServer.Stop() failes!", ex);
                    error = ex;
                }

                try
                {
                    foreach (var sock in connectedSockets.Values)
                    {
                        sock.Close();
                    }
                }
                catch (SocketException ex)
                {
                    //During one socket disconnected we can faced exception
                    theLog.Log.Error("TcpServer: close accepted socket failes!", ex);
                    error = ex;
                }
                if ( error != null )
                    throw error;
            }
        }


        private void OnSocketConnected(IPEndPoint ipEndPoint)
        {
            var handler = SocketConnected;
            if (handler != null)
                handler(this, new IPEndPointEventArgs(ipEndPoint));
        }

        private void OnSocketDisconnected(IPEndPoint ipEndPoint)
        {
            var handler = SocketDisconnected;
            if (handler != null)
                handler(this, new IPEndPointEventArgs(ipEndPoint));
        }
        private void OnDataReceived(byte[] data, IPEndPoint ipEndPoint)
        {
            var handler = DataReceived;
            if ( handler != null )
                handler(this, new DataReceivedEventArgs(data, ipEndPoint));
        }

        #endregion Private Functions

        //----------------------------------------------------------------------
        //Private Fields
        //----------------------------------------------------------------------
        #region Private Fields
        private const int SocketBufferSize = 1024;
        private readonly TcpListener tcpServer;
        private bool disposed;
        private readonly Dictionary<IPEndPoint, Socket> connectedSockets;
        private readonly object connectedSocketsSyncHandle = new object();
        #endregion Private Fields
    }
}

【讨论】:

  • 感谢这个 Sergey - 我现在正在阅读你的源代码以掌握它。我是那些喜欢理解事物而不仅仅是复制粘贴的小伙子之一......
  • 我认为这就是我要走的路 - 使用 IO Completion 端口的东西。感谢您提供完整的代码,但我不会简单地剪切和粘贴。正如我之前所说,我想了解某些东西为什么有效,因此我将使用您的作为参考来实现我自己的服务器类。干杯!
  • 有关 Winsocks API(以及使用 IO 完成端口)的更多信息,我推荐这本书:“Microsoft Windows 网络编程”,第二版(关于 Windows 网络编程的最佳书籍之一),以及Windows via C/C++ by Jeffrey Richter(关于 Win32、多线程和 IO 完成端口的最佳书籍之一)。我很高兴能帮上忙!
【解决方案2】:

制作多线程服务器非常简单。看看这个例子。

class Server
{
    private Socket socket;
    private List<Socket> connections;
    private volatile Boolean endAccept;

    // glossing over some code.


    /// <summary></summary>
    public void Accept()
    {
        EventHandler<SocketAsyncEventArgs> completed = null;
        SocketAsyncEventArgs args = null;

        completed = new EventHandler<SocketAsyncEventArgs>((s, e) =>
        {
            if (e.SocketError != SocketError.Success)
            {
                // handle
            }
            else
            {
                connections.Add(e.AcceptSocket);
                ThreadPool.QueueUserWorkItem(AcceptNewClient, e.AcceptSocket);
            }

            e.AcceptSocket = null;
            if (endAccept)
            {
                args.Dispose();
            }
            else if (!socket.AcceptAsync(args))
            {
                completed(socket, args);
            }
        });

        args = new SocketAsyncEventArgs();
        args.Completed += completed;

        if (!socket.AcceptAsync(args))
        {
            completed(socket, args);
        }
    }

    public void AcceptNewClient(Object state)
    {
        var socket = (Socket)state;
        // proccess        
    }        
}

【讨论】:

  • 感谢 ChoasPandion 的回复...不幸的是,我现在正在出门,但我稍后会看看这个。拉姆达函数是吗?仍然对语法有所了解...
  • 如果有什么不明白的地方请告诉我,我会继续展开。
  • 我们可以使用 BeginAcceptSocket 代替。
  • 使用 AcceptAsync 有一个明显的优势。使用 BeginAccept 时,您每次都需要创建一个新的 IAsyncResult 对象。对于高性能服务器,您希望将对象创建降至最低。使用此方法,您可以创建一个对象并在服务器期间使用它。
  • Choas/Sergey,感谢您的 cmets。但是,此对象创建开销可能有多大?我认为,如果它像 Sergey 建议的那样简单,那么避免处理线程可能会更简单......
【解决方案3】:

主要处理移动网络的人的一些建议:使用常规网络连接做作业,最好在本地主机上。这将在测试期间为您节省大量时间,并让您保持清醒,直到您找到最适合您的方法。

对于某些特定的实现,我总是使用同步套接字(如果出现问题,您需要配置超时以防止卡住)并且所有内容都在单独的线程中运行,这些线程在事件的帮助下同步。它比你想象的要简单得多。这里有一些有用的链接可以帮助您入门:

【讨论】:

  • 干杯 - 我将添加到要查看的内容列表中......谁认为这会很有趣,嗯?
【解决方案4】:

我现在正在编写相同的应用程序,我使用这样的解决方案:

http://clutch-inc.com/blog/?p=4

它现在已经过测试并且运行良好。重要的是使此服务仅用于接收和存储消息(某处)而无需其他工作。我使用NServiceBus 来保存消息。其他服务从队列中获取消息并完成剩下的工作。

【讨论】:

  • 谢谢达里奥 - 我也会调查那个。
【解决方案5】:

嗯,C# 语法现在在我的脑海中并不新鲜,但我认为它与 Posix 标准没有太大不同。

您可以做的是,当您创建侦听套接字时,您可以为 backlog 指定一个值(该服务器的最大同时连接数)并创建一个相同大小的线程拉取。线程池比传统的更容易使用。你在 backlog 参数上面为你排队的所有连接的 TCP。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多