首页 新闻 会员 周边 捐助

关于Socket服务器 谢谢大家 理解有限(大概200-500台设备作为客户端) 每台设备数据以每秒50MS的速度发送

0
悬赏园豆:5 [已关闭问题] 关闭于 2015-11-20 15:31

为了测试多台设备数据并发的问题,我需要选择同步或者异步方式的Socket服务端,于是写了两个来测试.我发现差不多的代码 取得的结果却不一样,你们看看,我代码哪里错了,数据都可以正常接收,只不过我加了一个合包处理.异步服务端取得的结果是错的。同步+多线程是正常的。折腾死了,希望大家帮帮忙。我需要做一个可以供200-500台设备数 据并发的服务端。

异步:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;

namespace SocketServer
{
    class Program
    {
        static byte[] buffer = new byte[1024];
        static IDictionary<Socket, byte[]> socketClientSesson = new Dictionary<Socket, byte[]>();
        static void Main(string[] args)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.103"), 4001));
            socket.Listen(500);

            while (true)
            {
                IAsyncResult result = socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
                result.AsyncWaitHandle.WaitOne();

            };
        }

        public static void ClientAccepted(IAsyncResult ar)
        {
            if (!ar.IsCompleted)
            {
                return;
            }
            var socket = ar.AsyncState as Socket;
            var client = socket.EndAccept(ar);
            socketClientSesson.Add(client, buffer);
            if (client.Connected)
            {
                try
                {
                    Console.WriteLine(Encoding.Unicode.GetBytes("Message from server at " + DateTime.Now.ToString()));
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
                socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            }
            else
            {
                Console.WriteLine("Client is disconnected, the timer is stop.");
            }

        }

        public static void ReceiveMessage(IAsyncResult ar)
        {

            try
            {
                var socket = ar.AsyncState as Socket;
                if (socket == null || !socketClientSesson.ContainsKey(socket))
                {
                    return;
                }
                var length = socket.EndReceive(ar);
                byte[] buf = socketClientSesson[socket];
                Array.Copy(buffer, buf, buf.Length);

                ByteQueue queue = new ByteQueue();
                queue.Enqueue(buf);
                while (queue.Find())
                {
                    byte[] readBuffer = queue.Dequeue();
                    var message = BitConverter.ToString(readBuffer);
                    if (message.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && message.EndsWith("EA-EB-EC-ED"))
                    {
                        string repStr = message.Replace("-", " ");
                        Regex regex = new Regex("07 81 08.{24}");
                        MatchCollection matches = regex.Matches(repStr, 0);
                        if (matches.Count > 0)
                        {
                            //显示消息
                            Console.WriteLine(message);
                        }
                    }
                }
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

 

同步:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication41
{
    class Program
    {
        Socket serverSocket;
        string tempIP = "";
        List<IPAddress> ipaddrssList = new List<IPAddress>();
        static void Main(string[] args)
        {
            new Program().ServerStar();
        }

        /// <summary>
        /// 建立连接
        /// </summary>
        private void ServerStar()
        {
            this.SocketServer("192.168.0.103", 4001);
        }

        /// <summary>
        /// 服务端
        /// </summary>
        private void SocketServer(string host, int port)
        {
            try
            {
                //服务器IP地址
                IPAddress ip = IPAddress.Parse(host);
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(new IPEndPoint(ip, port));
                serverSocket.Listen(500);
                Thread myThread = new Thread(ListenClientConnect);
                myThread.Start();
            }

            catch (ArgumentNullException ex)
            {
            }
            catch (SocketException ex)
            {
            }
        }

        /// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private void ListenClientConnect()
        {
            try
            {
                while (true)
                {
                    Socket clientSocket = serverSocket.Accept();
                    if (clientSocket.Connected == true)
                    {
                        Thread thread = new Thread(new ParameterizedThreadStart(ReceiveMessage));
                        thread.Start(clientSocket);
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>  
        /// 接收消息  
        /// </summary>  
        /// <param name="clientSocket"></param>  
        private void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            IPAddress clientIP = ((IPEndPoint)myClientSocket.RemoteEndPoint).Address;
            ByteQueue queue = new ByteQueue();
            int temp = 0;
            while (true)
            {
                try
                {
                    byte[] recvBytes = new byte[1024];
                    int bytes = myClientSocket.Receive(recvBytes, recvBytes.Length, 0);
                    byte[] reallData = new byte[bytes];
                    Array.Copy(recvBytes, reallData, reallData.Length);
                    queue.Enqueue(reallData);
                    while (queue.Find())
                    {
                        byte[] readBuffer = queue.Dequeue();
                        string data = BitConverter.ToString(readBuffer);
                        if (data.StartsWith("FF-FF-FF-FF-CA-CB-CC-CD") && data.EndsWith("EA-EB-EC-ED"))
                        {
                            string repStr = data.Replace("-", " ");
                            Regex regex = new Regex("07 81 08.{24}");
                            MatchCollection matches = regex.Matches(repStr, 0);
                            if (matches.Count > 0)
                            {
                                //显示消息
                                Console.WriteLine(repStr);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
        }
    }
}

 

何小宝的主页 何小宝 | 初学一级 | 园豆:19
提问于:2015-11-18 15:26
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册