/SimpleTcp/SimpleTcpServer/Program.cs
C# | 352 lines | 199 code | 47 blank | 106 comment | 29 complexity | fec5b958b9a0d713434b8261d6a55c3c MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.Diagnostics;
-
- namespace SimpleTcpServer
- {
-
- public class clSession
- {
- public int _ID;
- public Socket _Socket;
- public clSession(Socket ClientSocket)
- {
- Debug.Assert(ClientSocket != null);
- _Socket = ClientSocket;
- _ID = (int)ClientSocket.Handle;
- }
-
- public void Close()
- {
- Debug.Assert(_Socket != null);
- _Socket.Shutdown(SocketShutdown.Both);
- _Socket.Close();
- }
- }
-
- class TcpServer
- {
- public const int DefaultMaxClient = 5;
- public const int DefaultRecvBuffSize = 4 * 1024;
-
- private bool _bRun;
- private ushort _Port;
- private ushort _MaxClient;
- private TcpListener _Listener;
- private Dictionary<int, clSession> _dicSession;
- private byte[] _RecvBuff;
-
- protected void DoAcceptSocketCallback(IAsyncResult Result)
- {
- if (!_bRun)
- {
- Console.WriteLine("Server is not running...!!");
- return;
- }
-
- // Get the listener that handles the client request.
- TcpListener listener = (TcpListener)Result.AsyncState;
-
- // End the operation and display the received data on the
- //console.
- Socket NewSocket = listener.EndAcceptSocket(Result);
-
- // Process the connection here. (Add the client to a
- // server table, read data, etc.)
- if (_dicSession.Count() < _MaxClient)
- {
- _dicSession.Add((int)NewSocket.Handle, new clSession(NewSocket));
- Console.WriteLine("One client connected. Session ID = {0}", (int)NewSocket.Handle);
- NewSocket.BeginReceive(_RecvBuff, 0, _RecvBuff.Length, SocketFlags.None, new AsyncCallback(DoReceiveCallback), NewSocket);
- }
- else
- Console.WriteLine("Server is full!!");
-
- _Listener.BeginAcceptSocket(new AsyncCallback(DoAcceptSocketCallback), _Listener);
- }
-
- protected void DoReceiveCallback(IAsyncResult Result)
- {
- Socket ClientSocket = (Socket)Result.AsyncState;
- try
- {
- int RecvSize = ClientSocket.EndReceive(Result);
- if (RecvSize == 0)
- {
- CloseClient(ClientSocket);
- return;
- }
- Console.WriteLine("[{0}][Receive Message]: {1}", (int)ClientSocket.Handle, Encoding.ASCII.GetString(_RecvBuff, 0, RecvSize));
- ClientSocket.BeginReceive(_RecvBuff, 0, _RecvBuff.Length, SocketFlags.None, new AsyncCallback(DoReceiveCallback), ClientSocket);
- }
- catch (SocketException ex)
- {
- if (ex.ErrorCode == 10054)
- CloseClient(ClientSocket);
- }
- catch (ObjectDisposedException ex)
- {
- if (ex != null)
- ex = null;
- }
- }
-
- public TcpServer(ushort Port): this(Port, DefaultMaxClient)
- {
- }
-
- public TcpServer(ushort Port, ushort MaxClient)
- {
- _Port = Port;
- _MaxClient = MaxClient;
- }
-
- public void Start()
- {
- if (_bRun)
- {
- Console.WriteLine("Server is running...!!");
- return;
- }
-
- _dicSession = new Dictionary<int, clSession>(_MaxClient);
- _RecvBuff = new byte[DefaultRecvBuffSize];
- //System.Net.IPAddress theIPAddress;
- ////?? IPAddress ??(??)
- //theIPAddress = System.Net.IPAddress.Parse("127.0.0.1");
- //_Listener = new TcpListener(theIPAddress, _Port);
- IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
- _Listener = new TcpListener(ipAddress, _Port);
- _Listener.Start();
- _Listener.BeginAcceptSocket(new AsyncCallback(DoAcceptSocketCallback), _Listener);
- Console.WriteLine("Server Started...Listen at {0}...!!", _Listener.LocalEndpoint.ToString());
-
- _bRun = true;
- }
-
- public void Stop()
- {
- if (!_bRun)
- {
- Console.WriteLine("Server is not running...!!");
- return;
- }
- _bRun = false;
- _Listener.Stop();
- CloseAllClient();
- _dicSession = null;
- }
-
- public void Send(int SessionID, string Message)
- {
- clSession session = _dicSession[SessionID];
- if (session != null)
- {
- //byte[] data = _coder.GetEncodingBytes(datagram);
- Byte[] data = Encoding.ASCII.GetBytes(Message);
-
- //session._Socket.BeginSend(data, 0, data.Length, SocketFlags.None,
- // new AsyncCallback(SendDataEnd), session._Socket);
- //session._Socket.BeginSend(data, 0, data.Length, SocketFlags.None,
- //new AsyncCallback(SendDataEnd), session._Socket);
- session._Socket.Send(data, data.Length, 0);
- }
- }
-
- public void Broadcast(string Message)
- {
- Byte[] data = Encoding.ASCII.GetBytes(Message);
- foreach (clSession session in _dicSession.Values)
- session._Socket.Send(data, data.Length, 0);
- }
-
- public void CloseClient(Socket ClientSocket)
- {
- clSession session = _dicSession[(int)ClientSocket.Handle];
- session.Close();
- _dicSession.Remove((int)ClientSocket.Handle);
- Console.WriteLine("Session[{0}] is disconnected!!", (int)ClientSocket.Handle);
- }
-
- public void CloseAllClient()
- {
- foreach (clSession session in _dicSession.Values)
- session.Close();
- _dicSession.Clear();
- }
- }
-
- class Program
- {
- //public static void AcceptWorker(object Params)
- //{
- // Console.WriteLine("Accept Thread Starts.");
- // TcpListener Listener = (TcpListener)Params;
-
- // while (true)
- // {
- // Socket NewSocket = Listener.AcceptSocket();
- // if (NewSocket.Connected)
- // {
- // Console.WriteLine("???? !!");
- // clSession NewState = new clSession(NewSocket);
- // //NewState.ConnectionSocket = NewSocket;
- // Thread RecvThread = new Thread(Program.RecvWorker);
- // RecvThread.IsBackground = true;
- // RecvThread.Start(NewState);
- // }
- // }
- //}
-
- //public static void RecvWorker(object Params)
- //{
- // clSession state = (clSession)Params;
- // Console.WriteLine("Recv Thread Starts.");
- // //NetworkStream NetworkStream;
- // int dataLength;
- // byte[] myBufferBytes = new byte[1000];
-
- // while (true)
- // {
- // try
- // {
- // //??????????
- // dataLength = state.ConnectionSocket.Receive(myBufferBytes);
-
- // Console.WriteLine("???????? {0} \n ", dataLength.ToString());
- // Console.WriteLine("????????????????? :");
- // Console.WriteLine(Encoding.ASCII.GetString(myBufferBytes, 0, dataLength) + "\n");
- // //Console.WriteLine("?? [???] ????????? !!");
- // //Console.ReadLine();
- // //?????????????
- // //state.ConnectionSocket.Send(myBufferBytes, myBufferBytes.Length, 0);
- // state.ConnectionSocket.Send(myBufferBytes, dataLength, 0);
- // System.Threading.Thread.Sleep(100);
- // }
- // catch (Exception e)
- // {
- // Console.WriteLine(e.Message);
- // state.ConnectionSocket.Close();
- // break;
- // }
- // }
- //}
-
- static void Main(string[] args)
- {
- //System.Net.IPAddress theIPAddress;
- ////?? IPAddress ??(??)
- //theIPAddress = System.Net.IPAddress.Parse("127.0.0.1");
-
- ////??????
- //TcpListener Listener = new TcpListener(theIPAddress, 36000);
- ////????
- //Listener.Start();
- //Console.WriteLine("??? 36000 ???????...... !!");
- TcpServer tcpServer = new TcpServer(55000, 10);
-
-
- //Thread AcceptThread = new Thread(Program.AcceptWorker);
- //AcceptThread.IsBackground = true;
- //AcceptThread.Start(Listener);
- // Socket mySocket = myTcpListener.AcceptSocket();
- //do
- //{
- //try
- //{
- // //??????????????????
- // //?????????????????
- // if (mySocket.Connected)
- // {
- // int dataLength;
- // Console.WriteLine("???? !!");
- // byte[] myBufferBytes = new byte[1000];
- // //??????????
- // dataLength = mySocket.Receive(myBufferBytes);
-
- // Console.WriteLine("???????? {0} \n ", dataLength.ToString());
- // Console.WriteLine("????????????????? :");
- // Console.WriteLine(Encoding.ASCII.GetString(myBufferBytes, 0, dataLength) + "\n");
- // Console.WriteLine("?? [???] ????????? !!");
- // Console.ReadLine();
- // //?????????????
- // mySocket.Send(myBufferBytes, myBufferBytes.Length, 0);
- // }
- //}
- //catch (Exception e)
- //{
- // Console.WriteLine(e.Message);
- // mySocket.Close();
- // break;
- //}
- //} while (true);
- while (true)
- {
- //Console.Write(">");
-
- string cmd = Console.ReadLine();
-
- //??????
- if (cmd.ToLower() == "exit")
- {
- tcpServer.Stop();
- break;
- }
-
- if (cmd.ToLower() == "start")
- {
- tcpServer.Start();
- continue;
- }
-
- if (cmd.ToLower() == "stop")
- {
- tcpServer.Stop();
-
- Console.WriteLine("Server is Stop.");
-
- continue;
- }
-
- if (cmd.ToLower().IndexOf("send") != -1)
- {
- cmd = cmd.ToLower();
-
- string[] para = cmd.Split(' ');
-
- if (para.Length == 3)
- tcpServer.Send(int.Parse(para[1]), para[2]);
- else
- {
- Console.WriteLine("Error Command");
- }
-
- continue;
- }
-
- if (cmd.ToLower().IndexOf("bc") != -1)
- {
- cmd = cmd.ToLower();
-
- string[] para = cmd.Split(' ');
-
- if (para.Length == 2)
- tcpServer.Broadcast(para[1]);
- else
- {
- Console.WriteLine("Error Command");
- }
-
- continue;
- }
-
- Console.WriteLine("Unkown Command");
- }//end of while
- }
- }
- }