Advertisement
Guest User

С# network communicating

a guest
Apr 20th, 2013
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.62 KB | None | 0 0
  1. //Ниже приведены сегменты кода. Сегменты разделены комментариями.
  2. //server  цикл обработки клиента
  3. private void worker(object data)
  4.         {
  5.             string lastMessage = "";
  6.             if (data != null)
  7.             {
  8.                 var cvars = (connectionVars) data;
  9.                 NetworkStream local_ns = cvars.user.TcpClient.GetStream();
  10.                 systemMessages.Add("starting worker for " + cvars.user.TcpClient.Client.RemoteEndPoint + ", id = " +
  11.                                    cvars.user.id);
  12.                 systemMessages.Add("Call login for " + cvars.user.id);
  13.  
  14.                 if (login(cvars.user, local_ns)) //if success login
  15.                 {
  16.                     cvars.controls.currentOwner = users[cvars.user.user].login;
  17.                     systemMessages.Add("User logged in " + users[cvars.user.user].login);
  18.                     var loginData = new loginSC(cvars.user.access, cvars.user.id);
  19.                     cvars.user.message = string.Empty;
  20.                     Functions.SendData(local_ns, loginData);
  21.                     char oldCmd = 'C';
  22.  
  23.                     #region цикл обработки
  24.  
  25.                     while (cvars.user.avalible() && CarsServer_enabled && !users[cvars.user.user].banned)
  26.                     {
  27.                         //reserve commands, send commands to commands list.
  28.                         //like this:
  29.                         try
  30.                         {
  31.                             var s = (char) 0;
  32.  
  33.                             var datacs = Functions.ReserveData<dataCS>(local_ns);
  34.  
  35.                             s = datacs.cmd;
  36.  
  37.                             if (cvars.user.id == datacs.id)
  38.                             {
  39.                                 if (oldCmd != s)
  40.                                 {
  41.                                     oldCmd = s;
  42.                                     turn.Add(s);
  43.                                     //systemMessages.Add("Reserved " + s + " from " + cvars.user.id);
  44.                                 }
  45.                                 var datasc = new dataSC(true, "ok");
  46.                                 if (users[cvars.user.user].message != string.Empty)
  47.                                 {
  48.                                     lastMessage = users[cvars.user.user].message;
  49.                                     datasc = new dataSC(true, users[cvars.user.user].message);
  50.                                     users[cvars.user.user].message = string.Empty;
  51.                                 }
  52.                                 Functions.SendData(local_ns, datasc);
  53.                             }
  54.                             else
  55.                             {
  56.                                 var datasc = new dataSC(false,
  57.                                                         "Personal id corrupt. (Got " + datacs.id + "), user " +
  58.                                                         users[cvars.user.user].login);
  59.                                 Functions.SendData(local_ns, datasc);
  60.                                 break;
  61.                             }
  62.                         }
  63.                         catch (Exception ex)
  64.                         {
  65.                             systemMessages.Add("Видимо, пользователь " + users[cvars.user.user].login + " отключился: " +
  66.                                                ex.Message);
  67.  
  68.                             cvars.controls.currentOwner = "nobody";
  69.                             local_ns.Close();
  70.                             cvars.controls.free = true;
  71.                             cvars.user.TcpClient.Close();
  72.                             users[cvars.user.user].loggedIn = false;
  73.                         }
  74.                     }
  75.  
  76.                     #endregion
  77.  
  78.                     if (users[cvars.user.user].banned)
  79.                     {
  80.                         var datacs = Functions.ReserveData<dataCS>(local_ns); //заглушка для бана
  81.                         systemMessages.Add("Соединение будет закрыто по причине бана пользователя " +
  82.                                            users[cvars.user.user].login + ", причина: " + lastMessage);
  83.                         var datasc = new dataSC(false, users[cvars.user.user].message);
  84.                         Functions.SendData(local_ns, datasc);
  85.                     }
  86.                     cvars.controls.currentOwner = "noobody";
  87.                     local_ns.Close();
  88.                     cvars.controls.free = true;
  89.                     cvars.user.TcpClient.Close();
  90.                     users[cvars.user.user].loggedIn = false;
  91.                     return;
  92.                 }
  93.                 else
  94.                 {
  95.                     var loginData = new loginSC(false, 0);
  96.  
  97.  
  98.                     //byte[] loginDataB = Functions.ObjectToByteArray(loginData);
  99.                     //local_ns.Write(loginDataB, 0, loginDataB.Length);
  100.                     Functions.SendData(local_ns, loginData);
  101.  
  102.                     systemMessages.Add("Login failed for " + cvars.user.id);
  103.                     var message = new dataSC(false,
  104.                                              "You are not allowed to play. May be wrong login/password or u banned.");
  105.                     Functions.SendData(local_ns, message);
  106.                     //byte[] messageB = Functions.ObjectToByteArray(message);
  107.                     //local_ns.Write(messageB, 0, messageB.Length);
  108.                 }
  109.                 local_ns.Close();
  110.                 cvars.controls.free = true;
  111.             }
  112.         }
  113. //server
  114. где
  115.  
  116. //классы
  117.     internal class connectionVars  //переменные подключения для обработки клиента
  118.     {
  119.         public controller controls;
  120.         public NetworkStream stream;
  121.         public client user;
  122.  
  123.         public connectionVars(controller c, client u, NetworkStream s)
  124.         {
  125.             controls = c;
  126.             user = u;
  127.             stream = s;
  128.         }
  129.     }
  130.  
  131.  
  132.             //"пакеты"
  133.     [Serializable]
  134.     public class dataCS //от клиента к серверу
  135.     {
  136.         public char cmd;
  137.         public int id;
  138.  
  139.         public dataCS(char c, int i)
  140.         {
  141.             cmd = c;
  142.             id = i;
  143.         }
  144.     }
  145.  
  146.     [Serializable]
  147.     public class dataSC  //от сервера к клиенту
  148.     {
  149.         public bool access;
  150.         public string message;
  151.  
  152.         public dataSC(bool a, string m)
  153.         {
  154.             message = m;
  155.             access = a;
  156.         }
  157.     }
  158.  
  159. //классы
  160.  
  161. //функции
  162.  
  163.     public class functions
  164.     {
  165.         public long getSizeOf(object element)
  166.         {
  167.             long size = 0;
  168.             object obj = element;
  169.             using (Stream stream = new MemoryStream())
  170.             {
  171.                 var formatter = new BinaryFormatter();
  172.                 formatter.Serialize(stream, obj);
  173.                 size = stream.Length;
  174.             }
  175.             return size;
  176.         }
  177.  
  178.         public byte[] ObjectToByteArray(Object obj)
  179.         {
  180.             if (obj == null)
  181.                 return null;
  182.             var bf = new BinaryFormatter();
  183.             var ms = new MemoryStream();
  184.             bf.Serialize(ms, obj);
  185.             return ms.ToArray();
  186.         }
  187.  
  188.         public T ByteArrayToObject<T>(byte[] arrBytes)
  189.         {
  190.             var memStream = new MemoryStream();
  191.             var binForm = new BinaryFormatter();
  192.             memStream.Write(arrBytes, 0, arrBytes.Length);
  193.             memStream.Seek(0, SeekOrigin.Begin);
  194.             var obj = (T) binForm.Deserialize(memStream);
  195.             return obj;
  196.         }
  197.  
  198.         /// <summary>
  199.         ///     Прием данных с потока
  200.         /// </summary>
  201.         /// <typeparam name="T">Тип получаемых данных</typeparam>
  202.         /// <param name="stream">Поток для чтения</param>
  203.         /// <returns>Возвращает типа данных, заданный пользователем</returns>
  204.         public T ReserveData<T>(NetworkStream stream)
  205.         {
  206.             try
  207.             {
  208.                 T obj = default(T);
  209.                 long size = 0;
  210.                 var buffer = new byte[getSizeOf(size)];
  211.                 stream.Read(buffer, 0, buffer.Length);
  212.                 size = ByteArrayToObject<long>(buffer);
  213.                 var buffer2 = new byte[size];
  214.                 stream.Read(buffer2, 0, buffer2.Length);
  215.                 obj = ByteArrayToObject<T>(buffer2);
  216.                 return obj;
  217.             }
  218.             catch (Exception e)
  219.             {
  220.                 //MessageBox.Show("Failed to reserve data:" + e.Message);
  221.             }
  222.             return default(T);
  223.         }
  224.  
  225.         /// <summary>
  226.         ///     Отправка данных в поток
  227.         /// </summary>
  228.         /// <param name="stream">Поток для отправки</param>
  229.         /// <param name="o">данные для отправки</param>
  230.         /// <returns>Истина если все ок.</returns>
  231.         public bool SendData(NetworkStream stream, object o)
  232.         {
  233.             try
  234.             {
  235.                 byte[] buffer = ObjectToByteArray(o);
  236.                 byte[] sizeBytes = ObjectToByteArray((long) buffer.Length);
  237.                 stream.Write(sizeBytes, 0, sizeBytes.Length);
  238.                 stream.Write(buffer, 0, buffer.Length);
  239.                 return true;
  240.             }
  241.             catch (Exception e)
  242.             {
  243.                 //MessageBox.Show("Failed to send data:" + e.Message);
  244.             }
  245.             return false;
  246.         }
  247.     }
  248.  
  249. //функции
  250.  
  251. //клиент
  252.         private void timer1_Tick(object sender, EventArgs e)
  253.         {
  254.             char cmd = processKeys();
  255.             var datacs = new dataCS(cmd, ClientId);
  256.             Functions.SendData(ns, datacs);
  257.             Application.DoEvents();
  258.             var datasc = Functions.ReserveData<dataSC>(ns);
  259.  
  260.             if (datasc != null && !datasc.access)
  261.             {
  262.                 timer1.Enabled = false;
  263.                 if (datasc.message != null) WriteLog("Access denied with message: " + datasc.message);
  264.                 if (ns != null) ns.Close();
  265.                 if (client != null) client.Close();
  266.             }
  267.             if (datasc != null && datasc.message != "ok")
  268.                 WriteLog("Server message: " + datasc.message);
  269.         }
  270. //клиент
  271.  
  272.  
  273.  
  274.  
  275. //Функции и классы содержатся в подключаемой к клиенту и серверу либе
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement