Socketサーバコード

13985 ワード

public class SocketHost

{

private IDictionary<Socket, byte[]> socketClientSesson = new Dictionary<Socket, byte[]>();



public int Port { get; set; }



public void Start()

{

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(" ");

}



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.Handle.ToString();

Console.WriteLine(" ({0}) ", sessionId);

}

catch (Exception ex)

{

Console.WriteLine(" :\r
" + 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); Console.WriteLine(" :", context); this.Response(client, context); } catch (Exception ex) { Console.WriteLine(" :\r
{0}
", ex.ToString()); } } else { try { string sessionId = client.Handle.ToString(); client.Disconnect(true); this.socketClientSesson.Remove(client); Console.WriteLine(" ({0}) ", sessionId); } catch (Exception ex) { Console.WriteLine(" " + ex.ToString()); } } } private void Response(Socket sender, string context) { SocketRequest request = null; JavaScriptSerializer jss = new JavaScriptSerializer(); request = jss.Deserialize(context, typeof(SocketRequest)) as SocketRequest; if (request == null) { return; } var typeName = "SocketServer." + request.Method + "ResponseManager, SocketServer"; Console.WriteLine("" + typeName); Type type = Type.GetType(typeName); if (type == null) { return; } var manager = Activator.CreateInstance(type) as IResponseManager; manager.Write(sender, this.socketClientSesson.Select(s=> s.Key).ToList(), request.Param as IDictionary<string, object>); } }

 
 

Socketデータの非同期受信

#region  Socket 

/// <summary>

///  Socket 

/// </summary>

/// <param name="socket"></param>

/// <returns></returns>

public static byte[] ReceiveData(Socket socket)

{

    ReceiveObject state = new ReceiveObject() { Client = socket };

    socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), state);

    state.ReceiveDone.WaitOne(1000 * 10); // 10 

    byte[] result = state.Stream.ToArray();

    return result;

}

 

/// <summary>

///  

/// </summary>

private class ReceiveObject

{

    public Socket Client;

    public byte[] Buffer = new byte[4096];

    public System.IO.MemoryStream Stream = new System.IO.MemoryStream();

    public System.Threading.ManualResetEvent ReceiveDone = new System.Threading.ManualResetEvent(false);

}

 

/// <summary>

/// read 

/// </summary>

/// <param name="ar"></param>

private static void ReadCallback(IAsyncResult ar)

{

    ReceiveObject state = (ReceiveObject)ar.AsyncState;

    int bytesRead = state.Client.EndReceive(ar);

    if (bytesRead > 0)

    {

        try

        {

            state.Stream.Write(state.Buffer, 0, bytesRead);

            state.Client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), state);

        }

        catch (Exception ex)

        {

            Log.Error(ex.Message);

            state.ReceiveDone.Set();

        }

    }

    else

    {

        state.ReceiveDone.Set();

    }

}

#endregion