日期:2014-05-18 浏览次数:21086 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; using System.Threading; using System.Runtime.InteropServices; namespace nsqserver { [StructLayout(LayoutKind.Sequential)] public struct SendSegment { byte[] sendbuffer; SendPacketsElement[] sendelements; int offset; int count; public SendSegment(SendPacketsElement[] elements) { sendelements = elements; sendbuffer = null; offset = 0; count = 0; } public SendSegment(byte[] buffer, int ost, int cot) { sendbuffer = buffer; sendelements = null; offset = ost; count = cot; } public byte[] SendBuffer { get { return this.sendbuffer; } } public SendPacketsElement[] SendElments { get { return this.sendelements; } } public int Offset { get { return this.offset; } } public int Count { get { return this.count; } } } public enum RecvHasHeaders { On, Off } class SocketServer { byte[] buffers; byte[] sendbuffer; Socket[] sockets; SocketAsyncEventArgs[] sendargs; SocketAsyncEventArgs[] recvargs; SocketAsyncEventArgs[] acepargs; Queue<SendSegment>[] queues; Object[] objs; int recvbufferlen; int sockcount; int sendbufferlen; int sendindex; Object stackobj = new Object(); RecvHasHeaders[] recvhasheader; Socket acceptsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public event Func<int, byte[], int, int, int> RecvByteComplete; public event Func<int, byte[], int, int, int> RecvNoHeaderComplete; public event Action<int> SendPacketsComplete; public event Action<int> AcceptComplete; public event Action<int> SendComplete; public event Action<int> CloseComplete; byte[] inValue = new byte[] { 1, 0, 0, 0, 0x88, 0x13, 0, 0, 0x88, 0x13, 0, 0 }; public SocketServer(int skcount, int rvbufferlen, int sdbufferlen, int queuecount, string ipadr, int port) { buffers = new byte[skcount * rvbufferlen]; sendbufferlen = sdbufferlen; sendindex = 0; sendbuffer = new byte[sdbufferlen]; sockets = new Socket[skcount]; sendargs = new SocketAsyncEventArgs[skcount]; recvargs = new SocketAsyncEventArgs[skcount]; acepargs = new SocketAsyncEventArgs[skcount]; queues = new Queue<SendSegment>[skcount]; objs = new Object[skcount]; recvhasheader = new RecvHasHeaders[skcount]; recvbufferlen = rvbufferlen; sockcount = skcount; acceptsock.Bind(new IPEndPoint(IPAddress.Parse(ipadr), port)); acceptsock.Listen(100); for (int i = 0; i < skcount; i++) { sockets[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sendargs[i] = new SocketAsyncEventArgs(); sendargs[i]