用C#编写可以广播的SOCKET服务器端_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 用C#编写可以广播的SOCKET服务器端

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

 2012/6/18 15:15:45  dai_lm  程序员俱乐部  我要评论(0)
  • 摘要:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Net.Sockets;usingSystem.Net;usingSystem.IO;usingSystem.Web.Script.Serialization;namespaceSocketServer{publicclassSocketHost
  • 标签:C# 服务器 服务 socket
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();
        }
    }
}
发表评论
用户名: 匿名