关于昨天Socket服务器 问题再发一帖 谢谢大家 理解有限。

SomethingJack 2015-11-18 02:36:55
为了测试多台设备数据并发的问题,我需要选择同步或者异步方式的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)
{
}
}
}
}
}

...全文
89 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
SomethingJack 2015-11-18
  • 打赏
  • 举报
回复
引用 2 楼 diaodiaop 的回复:
LZ我记得你去年就开始玩socket了.. 现在怎么连同步异步还没玩明白吗? 加我好友吧...给你好东西.. 或许能解决你这2年没解决的问题..
这个搞清楚
引用 2 楼 diaodiaop 的回复:
LZ我记得你去年就开始玩socket了.. 现在怎么连同步异步还没玩明白吗? 加我好友吧...给你好东西.. 或许能解决你这2年没解决的问题..
之前掌握的东西 解决了我之前项目的问题,之前都是在枪炮的帮助下 再搞gdi+ TCP 仅限于会用 同步 异步 深入的没怎么理解 怎么加你?
by_封爱 版主 2015-11-18
  • 打赏
  • 举报
回复
LZ我记得你去年就开始玩socket了.. 现在怎么连同步异步还没玩明白吗? 加我好友吧...给你好东西.. 或许能解决你这2年没解决的问题..
本拉灯 2015-11-18
  • 打赏
  • 举报
回复
只能帮到你这了。这是最简单的方式了

 static IDictionary<Socket, ClientInfo> socketClientSesson = new Dictionary<Socket, ClientInfo>();
            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);

                socket.BeginAccept(new AsyncCallback(ClientAccepted), socket);
            }

            public static void ClientAccepted(IAsyncResult ar)
            {
                if (!ar.IsCompleted)
                {
                    return;
                }
                var socket = ar.AsyncState as Socket;
                var client = socket.EndAccept(ar);

                ClientInfo info = new ClientInfo();
                info.Queue = new ByteQueue();
                info.Buffer = new byte[1024];
                info.Socket = client;
                socketClientSesson.Add(client, info);

               
                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(info.Buffer, 0, info.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 class ClientInfo
            {
                public byte[] Buffer { get; set; }
                public ByteQueue Queue { get; set; }
                public Socket Socket { get; set; }
            }

            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);
                    ClientInfo info = socketClientSesson[socket];



                    byte[] readBuff = new byte[length];
                    System.Buffer.BlockCopy(info.Buffer, 0, readBuff, 0, length);


                   info.Queue.Enqueue(readBuff);
                   while (info.Queue.Find())
                    {
                        byte[] readBuffer = info.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(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧