当前位置:首页 > 开发 > 编程语言 > C# > 正文

用C#编写可以广播的SOCKET服务器端

发表于: 2012-06-12   作者:dai_lm   来源:转载   浏览:
摘要: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; using System.IO; using System.Web.Sc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace SocketServer
{
    public class SocketHost
    {
        private IDictionary<Socket, byte[]> socketClientSesson = new Dictionary<Socket, byte[]>();

        private List<string> message = new List<string>();
        private Boolean isClear = true;

        public int Port { get; set; }

        public void Start()
        {
            Boardcast();

            var socketThread = new Thread(() =>
            {
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, this.Port);

                //绑定到通道上
                socket.Bind(iep);

                //侦听
                socket.Listen(6);

                //通过异步来处理
                socket.BeginAccept(new AsyncCallback(Accept), socket);
            });

            socketThread.Start();

            Console.WriteLine("Server Started");
        }

        private void Accept(IAsyncResult ia)
        {
            Socket socket = ia.AsyncState as Socket;
            var client = socket.EndAccept(ia);

            socket.BeginAccept(new AsyncCallback(Accept), socket);

            byte[] buf = new byte[1024];
            this.socketClientSesson.Add(client, buf);

            try
            {
                client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
                string sessionId = client.RemoteEndPoint.ToString() + " - " + client.Handle.ToString();
                Console.WriteLine("Client ({0}) Connected", sessionId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:\r\n" + ex.ToString());
            }
        }

        private void Receive(IAsyncResult ia)
        {
            var client = ia.AsyncState as Socket;

            if (client == null || !this.socketClientSesson.ContainsKey(client))
            {
                return;
            }

            int count = client.EndReceive(ia);

            byte[] buf = this.socketClientSesson[client];

            if (count > 0)
            {
                try
                {
                    client.BeginReceive(buf, 0, buf.Length, SocketFlags.None, new AsyncCallback(Receive), client);
                    string context = Encoding.UTF8.GetString(buf, 0, count);
                    PushMessage(context);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Receive Error :\r\n{0}", ex.ToString());
                }
            }
            else
            {
                try
                {
                    string sessionId = client.RemoteEndPoint.ToString() + " - " + client.Handle.ToString();
                    client.Disconnect(true);
                    this.socketClientSesson.Remove(client);
                    Console.WriteLine("Client ({0}) Disconnet", sessionId);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: \r\n" + ex.ToString());
                }
            }
        }

        private void PushMessage(string context)
        {
            while (context.EndsWith("\n") || context.EndsWith("\0"))
            {
                context = context.Remove(context.Length - 1);
            }

            Console.WriteLine("Get : {0}", context); 
            message.Add(context);
            isClear = false;
        }

        private void Boardcast()
        {
            var boardcaseThread = new Thread(() =>
            {
                while (true)
                {
                    if (!isClear)
                    {
                        byte[] tmp = Encoding.UTF8.GetBytes(message[0] + "\0\n");
                        foreach (KeyValuePair<Socket, byte[]> node in this.socketClientSesson)
                        {
                            Socket client = node.Key;
                            client.Send(tmp, tmp.Length, SocketFlags.None);
                        }
                        message.RemoveAt(0);
                        isClear = message.Count > 0 ? false : true;
                    }
                }
            });

            boardcaseThread.Start();
        }
    }
}

用C#编写可以广播的SOCKET服务器端

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号