Advertisement
Guest User

Untitled

a guest
Jan 4th, 2013
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 16.70 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.NetworkInformation;
  7. using System.Net;
  8. using System.Threading;
  9. using System.Net.Sockets;
  10. using MySql.Data.MySqlClient;
  11.  
  12. namespace ConsoleApplication3
  13. {
  14.     class Program
  15.     {
  16.         class ThreadedServer
  17.         {
  18.             private Socket _serverSocket;
  19.             private int _port;
  20.             private string db_connect = "Database=test_login;Data Source=localhost;User Id=server;Password=qwerasdf";
  21.             private MySqlConnection myConnection;
  22.             private int id;
  23.  
  24.             public ThreadedServer(int port) { _port = port; }
  25.  
  26.             public void Start()
  27.             {
  28.                 myConnection = new MySqlConnection(db_connect);
  29.                
  30.                 SetupServerSocket();
  31.                 for (int i = 0; i < 10; i++)
  32.                     _serverSocket.BeginAccept(new
  33.                         AsyncCallback(AcceptCallback), _serverSocket);
  34.             }
  35.  
  36.             private class ConnectionInfo
  37.             {
  38.                 public Socket Socket;
  39.                 public byte[] Buffer;
  40.                 public int user_id;
  41.                 public int char_id;
  42.                 public int id;
  43.                 public string nick;
  44.                 public float x;
  45.                 public float y;
  46.                 public float z;
  47.  
  48.             }
  49.             private List<ConnectionInfo> _connections = new List<ConnectionInfo>();
  50.  
  51.             private void SetupServerSocket()
  52.             {
  53.                 // Получаем информацию о локальном компьютере
  54.                 /* IPHostEntry localMachineInfo =
  55.                      Dns.GetHostEntry(Dns.GetHostName());*/
  56.                 IPEndPoint myEndpoint = new IPEndPoint(IPAddress.Any, _port);
  57.  
  58.  
  59.                 // Создаем сокет, привязываем его к адресу
  60.                 // и начинаем прослушивание
  61.                 _serverSocket = new Socket(
  62.                     myEndpoint.Address.AddressFamily,
  63.                     SocketType.Stream, ProtocolType.Tcp);
  64.                 _serverSocket.Bind(myEndpoint);
  65.                 _serverSocket.Listen((int)
  66.                     SocketOptionName.MaxConnections);
  67.  
  68.             }
  69.  
  70.             private void AcceptCallback(IAsyncResult result)
  71.             {
  72.                 ConnectionInfo connection = new ConnectionInfo();
  73.                 try
  74.                 {
  75.                     // Завершение операции Accept
  76.                     Console.WriteLine("Подключился чел");
  77.                     Socket s = (Socket)result.AsyncState;
  78.                     connection.Socket = s.EndAccept(result);
  79.                     connection.Buffer = new byte[256];
  80.                     lock (_connections) _connections.Add(connection);
  81.  
  82.                     // Начало операции Receive и новой операции Accept
  83.                     connection.Socket.BeginReceive(connection.Buffer,
  84.                         0, connection.Buffer.Length, SocketFlags.None,
  85.                         new AsyncCallback(ReceiveCallback),
  86.                         connection);
  87.                     _serverSocket.BeginAccept(new AsyncCallback(
  88.                         AcceptCallback), result.AsyncState);
  89.                 }
  90.                 catch (SocketException exc)
  91.                 {
  92.                     CloseConnection(connection);
  93.                     Console.WriteLine("Socket exception: " +
  94.                         exc.SocketErrorCode);
  95.                 }
  96.                 catch (Exception exc)
  97.                 {
  98.                     CloseConnection(connection);
  99.                     Console.WriteLine("Exception: " + exc);
  100.                 }
  101.             }
  102.  
  103.             private void ReceiveCallback(IAsyncResult result)
  104.             {
  105.                 ConnectionInfo connection =
  106.                     (ConnectionInfo)result.AsyncState;
  107.                 try
  108.                 {
  109.                    
  110.                     int bytesRead =
  111.                         connection.Socket.EndReceive(result);
  112.                     if (0 != bytesRead)
  113.                     {
  114.                         lock (_connections)
  115.                         {
  116.                             string req = Encoding.UTF8.GetString(connection.Buffer, 0, 1);
  117.                             string all_req = Encoding.UTF8.GetString(connection.Buffer, 0, bytesRead);
  118.                             Console.WriteLine("comm = "+req);
  119.                             switch (req)
  120.                             {
  121.                                 case "%":
  122.                                     string[] split = all_req.Split(new Char[] { '%', '&', '%' });
  123.                                     id = Lreq_To_bd(split[1], split[2]); Console.WriteLine("id = "+id);
  124.                                     if (id != 0)
  125.                                     {
  126.                                         connection.id = id;
  127.                                         byte[] b = BitConverter.GetBytes(id);
  128.                                         Console.WriteLine("id = " + id);
  129.                                         connection.Socket.Send(b, b.Length, SocketFlags.None);
  130.                                         Console.WriteLine("Sended. Length = " + b.Length);
  131.                                     }
  132.                                     else
  133.                                     {
  134.                                         byte[] b = BitConverter.GetBytes(id);
  135.                                         //Console.WriteLine("id = " + id);
  136.                                         connection.Socket.Send(b, b.Length, SocketFlags.None);
  137.                                         Console.WriteLine("Sended. Length = " + b.Length);
  138.                                     }
  139.                                     break;
  140.                                 case "c":
  141.                                     int id_for_chars = BitConverter.ToInt32(connection.Buffer, 1);
  142.                                     Console.WriteLine(">> Запрос на список персов:\t" + Encoding.UTF8.GetString(connection.Buffer,0,1)+" "+id_for_chars);
  143.                                     byte[] bf = new byte[256];
  144.                                     bf = GetChars(id_for_chars);
  145.                                     connection.Socket.Send(bf, bf.Length, SocketFlags.None);
  146.                                     Console.WriteLine("Список персов послан:\t" + Encoding.UTF8.GetString(bf));
  147.                                     break;
  148.                                 case "h":
  149.                                     int id_for_new = BitConverter.ToInt32(connection.Buffer, 1);
  150.                                     int count = BitConverter.ToInt32(connection.Buffer, 5);
  151.                                     Console.WriteLine("bytes read = " + bytesRead);
  152.                                     string nick_for_new = Encoding.UTF8.GetString(connection.Buffer, 9, count);
  153.                                     byte[] bn = SetNewNick(id_for_new, nick_for_new);
  154.                                     connection.Socket.Send(bn, bn.Length, SocketFlags.None);
  155.                                     Console.WriteLine("Ошибка послана: "+Encoding.UTF8.GetString(bn,0,1)+"  "+BitConverter.ToInt32(bn,1));
  156.                                     break;
  157.                                 case "d":
  158.                                     int id_for_del = BitConverter.ToInt32(connection.Buffer, 1);
  159.                                     int count_del = BitConverter.ToInt32(connection.Buffer, 5);
  160.                                     string nick_for_del = Encoding.UTF8.GetString(connection.Buffer, 9, count_del);
  161.                                     DeleteChar(nick_for_del,id_for_del);
  162.                                     break;
  163.                                 case "g":
  164.                                     string nick_for_spawn = Encoding.UTF8.GetString(connection.Buffer, 5, BitConverter.ToInt32(connection.Buffer, 1));
  165.                                     byte[] bg = new byte[256];
  166.                                     bg = GetSpawn_and_CharID(nick_for_spawn);
  167.                                     connection.Socket.Send(bg, bg.Length, SocketFlags.None);
  168.                                     Console.WriteLine("Точки спавна отправленны");
  169.                                     break;
  170.                                 case "n":
  171.                                    
  172.                                      connection.user_id = BitConverter.ToInt32(connection.Buffer, 1);
  173.                                      connection.char_id = BitConverter.ToInt32(connection.Buffer, 5);
  174.                                      connection.x = BitConverter.ToInt32(connection.Buffer, 9);
  175.                                      connection.y = BitConverter.ToInt32(connection.Buffer, 13);
  176.                                      connection.z = BitConverter.ToInt32(connection.Buffer, 17);
  177.                                      connection.nick = Encoding.UTF8.GetString(connection.Buffer, 25, BitConverter.ToInt32(connection.Buffer, 21));
  178.                                      foreach (ConnectionInfo conn in _connections)
  179.                                 {
  180.                                     if (conn != connection)
  181.                                     {
  182.                                         conn.Socket.Send(connection.Buffer,connection.Buffer.Length, SocketFlags.None);
  183.                                         Console.WriteLine("new " + Encoding.UTF8.GetString(connection.Buffer, 0, connection.Buffer.Length));
  184.                                     }
  185.                                    
  186.                                 }
  187.                                     break;
  188.                                 default:
  189.                                     foreach (ConnectionInfo conn in _connections)
  190.                                     {
  191.                                         if (conn != connection)
  192.                                             conn.Socket.Send(connection.Buffer, connection.Buffer.Length, SocketFlags.None);
  193.  
  194.                                     }
  195.                                     break;
  196.                             }
  197.                          
  198.                         }
  199.                         connection.Socket.BeginReceive(
  200.                             connection.Buffer, 0,
  201.                             connection.Buffer.Length, SocketFlags.None,
  202.                             new AsyncCallback(ReceiveCallback),
  203.                             connection);
  204.                     }
  205.                     else CloseConnection(connection);
  206.                 }
  207.                 catch (SocketException exc)
  208.                 {
  209.                     CloseConnection(connection);
  210.                     Console.WriteLine("Socket exception: " +
  211.                         exc.SocketErrorCode);
  212.                 }
  213.                 catch (Exception exc)
  214.                 {
  215.                     CloseConnection(connection);
  216.                     Console.WriteLine("Exception: " + exc);
  217.                 }
  218.             }
  219.  
  220.             private void CloseConnection(ConnectionInfo ci)
  221.             {
  222.                 ci.Socket.Close();
  223.                 lock (_connections) _connections.Remove(ci);
  224.             }
  225.            
  226.             public int Lreq_To_bd(string l, string p)
  227.             {
  228.                 string request = "call GetId('"+l+"','"+p+"')";
  229.                
  230.                 MySqlCommand myCommand = new MySqlCommand(request, myConnection);
  231.                
  232.                 int value = 0;
  233.                 try
  234.                 {
  235.                     myConnection.Open();
  236.                     value = int.Parse(myCommand.ExecuteScalar().ToString());
  237.                     myConnection.Close();
  238.                     Console.WriteLine("value = " + value);
  239.                  
  240.                     Console.WriteLine("done sending req to bd. Value = " + value);
  241.                 }
  242.                 catch (Exception e) {
  243.                     myConnection.Close();
  244.                     Console.WriteLine("299 строка: "+e.Message); }
  245.  
  246.                 return value;
  247.             }
  248.  
  249.             public byte[] GetSpawn_and_CharID(string nick)
  250.             {
  251.                 byte[] buff = new byte[256];
  252.                 int point = 4;
  253.                 string query = "CALL GetSpawn_and_CharID('" + nick + "')";
  254.                 MySqlCommand myCommand = new MySqlCommand(query, myConnection);
  255.                 MySqlDataReader MyDataReader;
  256.                 myConnection.Open();
  257.                 MyDataReader = myCommand.ExecuteReader();
  258.                 MyDataReader.Read();
  259.  
  260.                 for (int i = 0; i < 3; i++)
  261.                 {
  262.                     BitConverter.GetBytes(MyDataReader.GetFloat(i)).CopyTo(buff,point);
  263.                     point += 4;
  264.                 }
  265.                 BitConverter.GetBytes(MyDataReader.GetInt32(3)).CopyTo(buff, point);
  266.  
  267.                 Encoding.UTF8.GetBytes("g").CopyTo(buff, 0);
  268.                  
  269.                 return buff;
  270.             }
  271.  
  272.             byte[] SetNewNick(int id, string nick)
  273.             {
  274.                
  275.                 byte[] b = new byte[256];
  276.                 Console.WriteLine("id for new = S" + id+"E   nick for new = S"+nick+"E");
  277.                 string str = "CALL SetNick('" + nick + "'," + id + ")";
  278.                 Console.WriteLine("запрос - " + str);
  279.                 MySqlCommand myCommand = new MySqlCommand(str, myConnection);
  280.                
  281.                 try
  282.                 {
  283.                     myConnection.Open();
  284.                     myCommand.ExecuteScalar();
  285.                     myConnection.Close();
  286.                     Encoding.UTF8.GetBytes("h").CopyTo(b, 0);
  287.                     BitConverter.GetBytes(1).CopyTo(b, 1);
  288.                     return b;
  289.                 }
  290.                 catch
  291.                 {
  292.                     byte[] bb = new byte[256];
  293.                     Encoding.UTF8.GetBytes("h").CopyTo(bb, 0);
  294.                     BitConverter.GetBytes(-1).CopyTo(bb, 1);
  295.                     return bb;
  296.                 }
  297.              
  298.             }
  299.  
  300.             void DeleteChar(string nick,int id)
  301.             {
  302.                 string str = "CALL DelNick(" + id + ",'" + nick + "')";
  303.                 MySqlCommand myCommand = new MySqlCommand(str, myConnection);
  304.                 myConnection.Open();
  305.                 myCommand.ExecuteScalar();
  306.                 myConnection.Close();
  307.             }
  308.  
  309.             byte[] GetChars(int id)
  310.             {
  311.                 byte[] bf = new byte[256];
  312.                 int num;
  313.                
  314.                 string str = "CALL get_num("+id+")";
  315.                 MySqlCommand myCommand = new MySqlCommand(str, myConnection);
  316.                 myConnection.Open();
  317.                 num = Convert.ToInt32(myCommand.ExecuteScalar().ToString());
  318.                 myConnection.Close();
  319.                 Console.WriteLine("num = "+num);
  320.                 if (num == 0)
  321.                 {
  322.                    
  323.                     return bf = Encoding.UTF8.GetBytes("0");  
  324.                 }
  325.                 else
  326.                 {
  327.                     bf = GetNick(id, num);
  328.                     BitConverter.GetBytes(num).CopyTo(bf, 1);
  329.                 }
  330.              
  331.                // byte[] b = Encoding.UTF8.GetBytes("c");
  332.                 //b.CopyTo(bf, 0);
  333.                 //BitConverter.GetBytes(num).CopyTo(bf, 1);
  334.                 return bf;
  335.             }
  336.             byte[] GetNick(int id, int i)
  337.             {
  338.                 byte[] bf = new byte[256];
  339.              
  340.                 Console.WriteLine("connected");
  341.                
  342.                 int point = 20;
  343.                 string query = "CALL get_chars("+id+")";
  344.                 MySqlCommand myCommand = new MySqlCommand(query, myConnection);
  345.                 MySqlDataReader MyDataReader;
  346.                 myConnection.Open();
  347.                 MyDataReader = myCommand.ExecuteReader();
  348.              
  349.                 while(MyDataReader.Read())
  350.                 {
  351.                    
  352.                     string s = MyDataReader.GetString(0);
  353.                
  354.                     Console.WriteLine("names = "+s);
  355.                    
  356.                     Encoding.UTF8.GetBytes(s).CopyTo(bf, point);
  357.                     point += 20;
  358.                 }
  359.                 myConnection.Close();
  360.                 byte[] bb = Encoding.UTF8.GetBytes("c");
  361.                 bb.CopyTo(bf, 0);
  362.                 return bf;
  363.             }
  364.            
  365.         }
  366.  
  367.  
  368.             static void Main(string[] args)
  369.             {
  370.                 ThreadedServer ts = new ThreadedServer(9390);
  371.  
  372.                 ts.Start();
  373.                 Console.ReadLine();
  374.  
  375.  
  376.  
  377.  
  378.  
  379.             }
  380.  
  381.  
  382.         }
  383.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement