Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 5.00/13: Рейтинг темы: голосов - 13, средняя оценка - 5.00
 Аватар для Игрок_со_Смерть
37 / 37 / 6
Регистрация: 06.01.2013
Сообщений: 195

Ассоциативный массив или его аналоги?

06.01.2013, 12:34. Показов 2506. Ответов 8
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Приветствую!

Недавно связался с языком c#, поэтому не судите строго если чего не знаю.

В общем суть такая, пишу приложение типа TeamViewer, только намного проще, возникла проблема в передачи данных от сервера к клиенту и обратно, но чтобы информацию передавать её сперва нужно преобразовать в понятный формат, чтобы небыло проблем с разбором.

в общем я решил сделать что то на подобии ассоциативного массива, то есть :

Метка => "Значение",

затем преобразую всё это в строку а потом в массив байт, но возникла проблема как на староне клиента из строки получить обратно такой же формат данных?
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
byte[] message;
       //var parameters = new Dictionary<string,string>();
 
        #region Формируем синхронизирующее сообщение для клиента
        //передаём ему ID, 
        //IP адресс сервера,
        //логин и пароль для подкл.чения
        public byte[] SyncMessageToClient(int ID, string serverIP, string userVPN, string passVPN) 
        {
 
            var SyncMessageToClient = new Dictionary<string, string>();//Создаём словарь типа "Метка" => Значение
            SyncMessageToClient.Add("serverIP", serverIP);
            SyncMessageToClient.Add("ID", ID.ToString());
            SyncMessageToClient.Add("userName", userVPN);
            SyncMessageToClient.Add("passVPN", passVPN);
            
           // string syncMessages = SyncMessageToClient.ToString();//Переводим словарь в строку 
           // message = Encoding.UTF8.GetBytes(syncMessages); // переводим строку в массив байт
         
            return message;// возвращяем массив байт
        }
        #endregion
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
06.01.2013, 12:34
Ответы с готовыми решениями:

Ассоциативный массив
Зрастье ;) Поставил себе задачу узнать оссоциативный массив в C#. Ну как бы узнал но те что хотел - Dictionary&lt;string, int&gt;...

Ассоциативный массив
приветствую. возможно ли в C# сделать так: $ar = Array( &quot;blabla&quot;=&gt;123 ); echo $ar;

Существуют ли аналоги webBrowser, например, на движке Мозиллы или Оперы
Существует ли webBrowser который использует движок IE, аналог любого другого движка к примеру firefox или opera&amp;&amp;

8
 Аватар для Doomer3D
180 / 180 / 32
Регистрация: 23.11.2012
Сообщений: 344
Записей в блоге: 1
06.01.2013, 14:11
Все гораздо проще, чем вы думаете.

Алгоритм кодирования словаря таков:
1. Записываем число элементов словаря - N.
2. В цикле по элементам словаря записываем 2N строки. Четные строки (0, 2 и т.д.) - это ключи, нечетные - значения.

Строка записывается аналогично: сперва длина строки, затем сама строка.

Считывание происходит в том же порядке, что и запись.

Вам понадобится метод преобразования строки в набор байт и наоборот, это методы GetBytes и GetString соответственно класса Encoding, например:

C#
1
Encoding.UTF8.GetBytes("Какая-то строка");
Добавлено через 2 минуты
А вообще, гораздо эффективнее передавать не строки, а уже готовые значения.
В спойлере класс для записи пакетов сервера Ultima Online, возможно, посмотрев его, станет немного понятней, как можно работать с сетью.

Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/***************************************************************************
 *                              PacketWriter.cs
 *                            -------------------
 *   begin                : May 1, 2002
 *   copyright            : (C) The RunUO Software Team
 *   email                : [email]info@runuo.com[/email]
 *
 *   $Id: PacketWriter.cs 114 2006-12-13 18:28:37Z mark $
 *
 ***************************************************************************/
 
/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/
 
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
 
namespace Server.Network
{
    /// <summary>
    /// Provides functionality for writing primitive binary data.
    /// </summary>
    public class PacketWriter
    {
        private static Stack<PacketWriter> m_Pool = new Stack<PacketWriter>();
 
        public static PacketWriter CreateInstance()
        {
            return CreateInstance( 32 );
        }
 
        public static PacketWriter CreateInstance( int capacity )
        {
            PacketWriter pw = null;
 
            lock ( m_Pool )
            {
                if ( m_Pool.Count > 0 )
                {
                    pw = m_Pool.Pop();
 
                    if ( pw != null )
                    {
                        pw.m_Capacity = capacity;
                        pw.m_Stream.SetLength( 0 );
                    }
                }
            }
 
            if ( pw == null )
                pw = new PacketWriter( capacity );
 
            return pw;
        }
 
        public static void ReleaseInstance( PacketWriter pw )
        {
            lock ( m_Pool )
            {
                if ( !m_Pool.Contains( pw ) )
                {
                    m_Pool.Push( pw );
                }
                else
                {
                    try
                    {
                        using ( StreamWriter op = new StreamWriter( "neterr.log" ) )
                        {
                            op.WriteLine( "{0}\tInstance pool contains writer", DateTime.Now );
                        }
                    }
                    catch
                    {
                        Console.WriteLine( "net error" );
                    }
                }
            }
        }
 
        /// <summary>
        /// Internal stream which holds the entire packet.
        /// </summary>
        private MemoryStream m_Stream;
 
        private int m_Capacity;
 
        /// <summary>
        /// Internal format buffer.
        /// </summary>
        private static byte[] m_Buffer = new byte[4];
 
        /// <summary>
        /// Instantiates a new PacketWriter instance with the default capacity of 4 bytes.
        /// </summary>
        public PacketWriter() : this( 32 )
        {
        }
 
        /// <summary>
        /// Instantiates a new PacketWriter instance with a given capacity.
        /// </summary>
        /// <param name="capacity">Initial capacity for the internal stream.</param>
        public PacketWriter( int capacity )
        {
            m_Stream = new MemoryStream( capacity );
            m_Capacity = capacity;
        }
 
        /// <summary>
        /// Writes a 1-byte boolean value to the underlying stream. False is represented by 0, true by 1.
        /// </summary>
        public void Write( bool value )
        {
            m_Stream.WriteByte( (byte)(value ? 1 : 0) );
        }
 
        /// <summary>
        /// Writes a 1-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write( byte value )
        {
            m_Stream.WriteByte( value );
        }
 
        /// <summary>
        /// Writes a 1-byte signed integer value to the underlying stream.
        /// </summary>
        public void Write( sbyte value )
        {
            m_Stream.WriteByte( (byte) value );
        }
 
        /// <summary>
        /// Writes a 2-byte signed integer value to the underlying stream.
        /// </summary>
        public void Write( short value )
        {
            m_Buffer[0] = (byte)(value >> 8);
            m_Buffer[1] = (byte) value;
 
            m_Stream.Write( m_Buffer, 0, 2 );
        }
 
        /// <summary>
        /// Writes a 2-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write( ushort value )
        {
            m_Buffer[0] = (byte)(value >> 8);
            m_Buffer[1] = (byte) value;
 
            m_Stream.Write( m_Buffer, 0, 2 );
        }
 
        /// <summary>
        /// Writes a 4-byte signed integer value to the underlying stream.
        /// </summary>
        public void Write( int value )
        {
            m_Buffer[0] = (byte)(value >> 24);
            m_Buffer[1] = (byte)(value >> 16);
            m_Buffer[2] = (byte)(value >>  8);
            m_Buffer[3] = (byte) value;
 
            m_Stream.Write( m_Buffer, 0, 4 );
        }
 
        /// <summary>
        /// Writes a 4-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write( uint value )
        {
            m_Buffer[0] = (byte)(value >> 24);
            m_Buffer[1] = (byte)(value >> 16);
            m_Buffer[2] = (byte)(value >>  8);
            m_Buffer[3] = (byte) value;
 
            m_Stream.Write( m_Buffer, 0, 4 );
        }
 
        /// <summary>
        /// Writes a sequence of bytes to the underlying stream
        /// </summary>
        public void Write( byte[] buffer, int offset, int size )
        {
            m_Stream.Write( buffer, offset, size );
        }
 
        /// <summary>
        /// Writes a fixed-length ASCII-encoded string value to the underlying stream. To fit (size), the string content is either truncated or padded with null characters.
        /// </summary>
        public void WriteAsciiFixed( string value, int size )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteAsciiFixed() with null value" );
                value = String.Empty;
            }
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + size );
 
            if ( length >= size )
                m_Stream.Position += Encoding.ASCII.GetBytes( value, 0, size, m_Stream.GetBuffer(), (int)m_Stream.Position );
            else
            {
                Encoding.ASCII.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
                m_Stream.Position += size;
            }
 
            /*byte[] buffer = Encoding.ASCII.GetBytes( value );
 
            if ( buffer.Length >= size )
            {
                m_Stream.Write( buffer, 0, size );
            }
            else
            {
                m_Stream.Write( buffer, 0, buffer.Length );
                Fill( size - buffer.Length );
            }*/
        }
 
        /// <summary>
        /// Writes a dynamic-length ASCII-encoded string value to the underlying stream, followed by a 1-byte null character.
        /// </summary>
        public void WriteAsciiNull( string value )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteAsciiNull() with null value" );
                value = String.Empty;
            }
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + length + 1 );
 
            Encoding.ASCII.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            m_Stream.Position += length + 1;
 
            /*byte[] buffer = Encoding.ASCII.GetBytes( value );
 
            m_Stream.Write( buffer, 0, buffer.Length );
            m_Stream.WriteByte( 0 );*/
        }
 
        /// <summary>
        /// Writes a dynamic-length little-endian unicode string value to the underlying stream, followed by a 2-byte null character.
        /// </summary>
        public void WriteLittleUniNull( string value )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteLittleUniNull() with null value" );
                value = String.Empty;
            }
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + ( ( length + 1 ) * 2 ) );
 
            m_Stream.Position += Encoding.Unicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            m_Stream.Position += 2;
 
            /*byte[] buffer = Encoding.Unicode.GetBytes( value );
 
            m_Stream.Write( buffer, 0, buffer.Length );
 
            m_Buffer[0] = 0;
            m_Buffer[1] = 0;
            m_Stream.Write( m_Buffer, 0, 2 );*/
        }
 
        /// <summary>
        /// Writes a fixed-length little-endian unicode string value to the underlying stream. To fit (size), the string content is either truncated or padded with null characters.
        /// </summary>
        public void WriteLittleUniFixed( string value, int size )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteLittleUniFixed() with null value" );
                value = String.Empty;
            }
 
            size *= 2;
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + size );
 
            if ( ( length * 2 ) >= size )
                m_Stream.Position += Encoding.Unicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            else
            {
                Encoding.Unicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
                m_Stream.Position += size;
            }
 
            /*size *= 2;
 
            byte[] buffer = Encoding.Unicode.GetBytes( value );
 
            if ( buffer.Length >= size )
            {
                m_Stream.Write( buffer, 0, size );
            }
            else
            {
                m_Stream.Write( buffer, 0, buffer.Length );
                Fill( size - buffer.Length );
            }*/
        }
 
        /// <summary>
        /// Writes a dynamic-length big-endian unicode string value to the underlying stream, followed by a 2-byte null character.
        /// </summary>
        public void WriteBigUniNull( string value )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteBigUniNull() with null value" );
                value = String.Empty;
            }
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + ( ( length + 1 ) * 2 ) );
 
            m_Stream.Position += Encoding.BigEndianUnicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            m_Stream.Position += 2;
 
            /*byte[] buffer = Encoding.BigEndianUnicode.GetBytes( value );
 
            m_Stream.Write( buffer, 0, buffer.Length );
 
            m_Buffer[0] = 0;
            m_Buffer[1] = 0;
            m_Stream.Write( m_Buffer, 0, 2 );*/
        }
 
        /// <summary>
        /// Writes a fixed-length big-endian unicode string value to the underlying stream. To fit (size), the string content is either truncated or padded with null characters.
        /// </summary>
        public void WriteBigUniFixed( string value, int size )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteBigUniFixed() with null value" );
                value = String.Empty;
            }
 
            size *= 2;
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + size );
 
            if ( ( length * 2 ) >= size )
                m_Stream.Position += Encoding.BigEndianUnicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            else
            {
                Encoding.BigEndianUnicode.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
                m_Stream.Position += size;
            }
 
            /*size *= 2;
 
            byte[] buffer = Encoding.BigEndianUnicode.GetBytes( value );
 
            if ( buffer.Length >= size )
            {
                m_Stream.Write( buffer, 0, size );
            }
            else
            {
                m_Stream.Write( buffer, 0, buffer.Length );
                Fill( size - buffer.Length );
            }*/
        }
 
        /// <summary>
        /// Fills the stream from the current position up to (capacity) with 0x00's
        /// </summary>
        public void Fill()
        {
            Fill( (int) (m_Capacity - m_Stream.Length) );
        }
 
        /// <summary>
        /// Writes a number of 0x00 byte values to the underlying stream.
        /// </summary>
        public void Fill( int length )
        {
            if ( m_Stream.Position == m_Stream.Length )
            {
                m_Stream.SetLength( m_Stream.Length + length );
                m_Stream.Seek( 0, SeekOrigin.End );
            }
            else
            {
                m_Stream.Write( new byte[length], 0, length );
            }
        }
 
        /// <summary>
        /// Gets the total stream length.
        /// </summary>
        public long Length
        {
            get
            {
                return m_Stream.Length;
            }
        }
 
        /// <summary>
        /// Gets or sets the current stream position.
        /// </summary>
        public long Position
        {
            get
            {
                return m_Stream.Position;
            }
            set
            {
                m_Stream.Position = value;
            }
        }
 
        /// <summary>
        /// The internal stream used by this PacketWriter instance.
        /// </summary>
        public MemoryStream UnderlyingStream
        {
            get
            {
                return m_Stream;
            }
        }
 
        /// <summary>
        /// Offsets the current position from an origin.
        /// </summary>
        public long Seek( long offset, SeekOrigin origin )
        {
            return m_Stream.Seek( offset, origin );
        }
 
        /// <summary>
        /// Gets the entire stream content as a byte array.
        /// </summary>
        public byte[] ToArray()
        {
            return m_Stream.ToArray();
        }
    }
}
0
 Аватар для Игрок_со_Смерть
37 / 37 / 6
Регистрация: 06.01.2013
Сообщений: 195
06.01.2013, 16:01  [ТС]
Получается обессмыслено использовать Dictonary, так как придется наворотить велосипед с преобразованием словаря в строку, а потом из строки в словарь=) А как на счёт Hashtable?
Кликните здесь для просмотра всего текста

C#
1
2
3
4
5
6
7
8
9
10
11
12
Hashtable ht = new Hashtable();
            ht.Add("ID", ID);
            ht.Add("serverIP", serverIP);
            ht.Add("userVPN", userVPN);
            ht.Add("passVPN", passVPN);
 
           // ICollection key = ht.Keys;
 
            foreach (string s in ht.Keys)
            {
                syncMessages = s + ": " + ht[s];
            }


ЗЫ: Почитал код приложенный, и понял что я далек от понимая =), что то понятно, что то нет, но согласно коду сообщение передается как обычно по битно, то есть строка передаваемая кодируется в биты путём кодировки каждого символа а потом отправляется, в потоке через сокет?
Не увидил реализации как передавать готовые значения?
0
 Аватар для Doomer3D
180 / 180 / 32
Регистрация: 23.11.2012
Сообщений: 344
Записей в блоге: 1
06.01.2013, 17:16
А с помощью чего вы собственно передаете данные по сети?
0
 Аватар для Игрок_со_Смерть
37 / 37 / 6
Регистрация: 06.01.2013
Сообщений: 195
06.01.2013, 17:22  [ТС]
потоку скармливаю массив байт и всё=)

Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
IPAddress ipAddress = IPAddress.Parse(textIP.Text); //  Привеодим к нужному виду IP адресс
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, int.Parse(textPort.Text)); // Создаём конечную точку подключения IP+Port
 
            Socket sLister = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Создаём потоковый сокет на основе протакола TCP ipv4
 
            try
            {
                sLister.Bind(ipEndPoint); // Назначаем нашему сокету конечную точку
                sLister.Listen(10); // Устанавливаем максимальное число соединений 10
 
                while (true) // Бесконечно ожидаем подключение клиента
                {
                    listLog.Items.Add("Ожидаем входящее подключени");
                    Socket handler = sLister.Accept(); // Ожидаем входящее пдключени
                    string data = null; //Создаём переменную типа string  устанавливаем ей значение по умолчанию null
 
                    while (true) // Дождались подключение клиента
                    {
                        byte[] buffer = new byte[1024]; // Создаём буфер в который будем помещать полученые данные
                        int bufferRecive = handler.Receive(buffer); // Помещаем полученые данные в buffer
                        data += Encoding.UTF8.GetString(buffer, 0, bufferRecive); //Устанавливаем переменной data значение перекодированого буфера
 
                        if (data.IndexOf("<TheEnd>") != -1)  // проверяем полученые данные на наличие конца сообщения
                        {
                            MessageBox.Show("Вроде работает");
                            break; // Останавливаем чтения сообщения
                        }
                    }
 
                    listLog.Items.Add(data); // Выводим полученые данные в консоль
 
                    string msgRespond = "Данные получены успешно" + data.Length.ToString(); // Формируем ответ
                    byte[] msg = Encoding.ASCII.GetBytes(msgRespond); // Переводим из string  в массив байт
 
                    handler.Send(msg); // шлём сообщение
                    handler.Shutdown(SocketShutdown.Both); // Отключаем передачу данных
                    handler.Close(); // Закрываем установленое соединение
                    break;
                }
 
            }
            catch (SocketException errors)
            {
                //Выводим построчно все сообщения с ошибками в Log в формате "Ошибка 'КОД ОШИБКИ': 'СООБЩЕНИЕ'"
                listLog.Items.Add(String.Format("Ошибка {0} : {1}", errors.ErrorCode, errors.Message));
            }  
        }
0
 Аватар для Doomer3D
180 / 180 / 32
Регистрация: 23.11.2012
Сообщений: 344
Записей в блоге: 1
06.01.2013, 17:33
У вас также используется сокет, также передаются массивы байт, так что можете воспользоваться прилагаемым мной файлом примера. Там идет запись в поток в памяти, например:

C#
1
2
3
4
5
6
7
        /// <summary>
        /// Writes a 1-byte unsigned integer value to the underlying stream.
        /// </summary>
        public void Write( byte value )
        {
            m_Stream.WriteByte( value );
        }
Или еще пример:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
        /// <summary>
        /// Writes a dynamic-length ASCII-encoded string value to the underlying stream, followed by a 1-byte null character.
        /// </summary>
        public void WriteAsciiNull( string value )
        {
            if ( value == null )
            {
                Console.WriteLine( "Network: Attempted to WriteAsciiNull() with null value" );
                value = String.Empty;
            }
 
            int length = value.Length;
 
            m_Stream.SetLength( m_Stream.Length + length + 1 );
 
            Encoding.ASCII.GetBytes( value, 0, length, m_Stream.GetBuffer(), (int)m_Stream.Position );
            m_Stream.Position += length + 1;
 
            /*byte[] buffer = Encoding.ASCII.GetBytes( value );
 
            m_Stream.Write( buffer, 0, buffer.Length );
            m_Stream.WriteByte( 0 );*/
        }
А когда все записано, получаем итоговый массив байт:

C#
1
2
3
4
5
6
7
        /// <summary>
        /// Gets the entire stream content as a byte array.
        /// </summary>
        public byte[] ToArray()
        {
            return m_Stream.ToArray();
        }
Конечно, мой пример - это кусок кода из сервера игры, но он дает представление о том, как можно формировать пакеты.
0
 Аватар для Игрок_со_Смерть
37 / 37 / 6
Регистрация: 06.01.2013
Сообщений: 195
06.01.2013, 17:56  [ТС]
Меня видимо маленько не понял =)

Как передать массив байт я знаю =) меня интересует как сформировать строку из параметров и значений на сервере, и как потом её на клиенте разобрать.
Нужен универсальное решение которое позволяло бы на стороне сервера собрать все нужные данные в строку:

ID=123456
UserVPN=User1
UserPass=testPass

ID=123456;UserVPN=User1;UserPass=testPas s;

имел входящие данные "ID" ... "N"
в результате выдавал строку ID=123456;UserVPN=User1;UserPass=testPas s;

А на стороне клиента обращается к этим данным типа

ID=parametr[ID];
0
 Аватар для Doomer3D
180 / 180 / 32
Регистрация: 23.11.2012
Сообщений: 344
Записей в блоге: 1
06.01.2013, 18:04
Это не лучший подход, но можно и так. Алгоритм в моем первом посте.

Пихаем в массив байт следующие строки:

ID
123456
UserVPN
User1
UserPass
testPass

На стороне клиента получаем эти же строки и формируем словарь, запихиваем это в словарь...

Добавлено через 43 секунды
Я как раз в данный момент клиент-сервер, но не уверен, что успею в ближайшее время дойти до этого момента, так бы дал готовый код.

Добавлено через 4 минуты
Вот, кстати, класс PacketReader из того же сервера:

Кликните здесь для просмотра всего текста
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/***************************************************************************
 *                              PacketReader.cs
 *                            -------------------
 *   begin                : May 1, 2002
 *   copyright            : (C) The RunUO Software Team
 *   email                : [email]info@runuo.com[/email]
 *
 *   $Id: PacketReader.cs 4 2006-06-15 04:28:39Z mark $
 *
 ***************************************************************************/
 
/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/
 
using System;
using System.Text;
using System.IO;
 
namespace Server.Network
{
    public class PacketReader
    {
        private byte[] m_Data;
        private int m_Size;
        private int m_Index;
 
        public PacketReader( byte[] data, int size, bool fixedSize )
        {
            m_Data = data;
            m_Size = size;
            m_Index = fixedSize ? 1 : 3;
        }
 
        public byte[] Buffer
        {
            get
            {
                return m_Data;
            }
        }
 
        public int Size
        {
            get
            {
                return m_Size;
            }
        }
 
        public void Trace( NetState state )
        {
            try
            {
                using ( StreamWriter sw = new StreamWriter( "Packets.log", true ) )
                {
                    byte[] buffer = m_Data;
 
                    if ( buffer.Length > 0 )
                        sw.WriteLine( "Client: {0}: Unhandled packet 0x{1:X2}", state, buffer[0] );
 
                    using ( MemoryStream ms = new MemoryStream( buffer ) )
                        Utility.FormatBuffer( sw, ms, buffer.Length );
 
                    sw.WriteLine();
                    sw.WriteLine();
                }
            }
            catch
            {
            }
        }
 
        public int Seek( int offset, SeekOrigin origin )
        {
            switch ( origin )
            {
                case SeekOrigin.Begin: m_Index = offset; break;
                case SeekOrigin.Current: m_Index += offset; break;
                case SeekOrigin.End: m_Index = m_Size - offset; break;
            }
 
            return m_Index;
        }
 
        public int ReadInt32()
        {
            if ( (m_Index + 4) > m_Size )
                return 0;
 
            return (m_Data[m_Index++] << 24)
                 | (m_Data[m_Index++] << 16)
                 | (m_Data[m_Index++] <<  8)
                 |  m_Data[m_Index++];
        }
 
        public short ReadInt16()
        {
            if ( (m_Index + 2) > m_Size )
                return 0;
 
            return (short)((m_Data[m_Index++] << 8) | m_Data[m_Index++]);
        }
 
        public byte ReadByte()
        {
            if ( (m_Index + 1) > m_Size )
                return 0;
 
            return m_Data[m_Index++];
        }
 
        public uint ReadUInt32()
        {
            if ( (m_Index + 4) > m_Size )
                return 0;
 
            return (uint)((m_Data[m_Index++] << 24) | (m_Data[m_Index++] << 16) | (m_Data[m_Index++] << 8) | m_Data[m_Index++]);
        }
 
        public ushort ReadUInt16()
        {
            if ( (m_Index + 2) > m_Size )
                return 0;
 
            return (ushort)((m_Data[m_Index++] << 8) | m_Data[m_Index++]);
        }
 
        public sbyte ReadSByte()
        {
            if ( (m_Index + 1) > m_Size )
                return 0;
 
            return (sbyte)m_Data[m_Index++];
        }
 
        public bool ReadBoolean()
        {
            if ( (m_Index + 1) > m_Size )
                return false;
 
            return ( m_Data[m_Index++] != 0 );
        }
 
        public string ReadUnicodeStringLE()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < m_Size && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 )
                sb.Append( (char)c );
 
            return sb.ToString();
        }
 
        public string ReadUnicodeStringLESafe( int fixedLength )
        {
            int bound = m_Index + (fixedLength << 1);
            int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < bound && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            m_Index = end;
 
            return sb.ToString();
        }
 
        public string ReadUnicodeStringLESafe()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < m_Size && (c = (m_Data[m_Index++] | (m_Data[m_Index++] << 8))) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            return sb.ToString();
        }
 
        public string ReadUnicodeStringSafe()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < m_Size && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            return sb.ToString();
        }
 
        public string ReadUnicodeString()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < m_Size && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 )
                sb.Append( (char)c );
 
            return sb.ToString();
        }
 
        public bool IsSafeChar( int c )
        {
            return ( c >= 0x20 && c < 0xFFFE );
        }
 
        public string ReadUTF8StringSafe( int fixedLength )
        {
            if ( m_Index >= m_Size )
            {
                m_Index += fixedLength;
                return String.Empty;
            }
 
            int bound = m_Index + fixedLength;
            //int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            int count = 0;
            int index = m_Index;
            int start = m_Index;
 
            while ( index < bound && m_Data[index++] != 0 )
                ++count;
 
            index = 0;
 
            byte[] buffer = new byte[count];
            int value = 0;
 
            while ( m_Index < bound && (value = m_Data[m_Index++]) != 0 )
                buffer[index++] = (byte)value;
 
            string s = Utility.UTF8.GetString( buffer );
 
            bool isSafe = true;
 
            for ( int i = 0; isSafe && i < s.Length; ++i )
                isSafe = IsSafeChar( (int) s[i] );
 
            m_Index = start + fixedLength;
 
            if ( isSafe )
                return s;
 
            StringBuilder sb = new StringBuilder( s.Length );
 
            for ( int i = 0; i < s.Length; ++i )
                if ( IsSafeChar( (int) s[i] ) )
                    sb.Append( s[i] );
 
            return sb.ToString();
        }
 
        public string ReadUTF8StringSafe()
        {
            if ( m_Index >= m_Size )
                return String.Empty;
 
            int count = 0;
            int index = m_Index;
 
            while ( index < m_Size && m_Data[index++] != 0 )
                ++count;
 
            index = 0;
 
            byte[] buffer = new byte[count];
            int value = 0;
 
            while ( m_Index < m_Size && (value = m_Data[m_Index++]) != 0 )
                buffer[index++] = (byte)value;
 
            string s = Utility.UTF8.GetString( buffer );
 
            bool isSafe = true;
 
            for ( int i = 0; isSafe && i < s.Length; ++i )
                isSafe = IsSafeChar( (int) s[i] );
 
            if ( isSafe )
                return s;
 
            StringBuilder sb = new StringBuilder( s.Length );
 
            for ( int i = 0; i < s.Length; ++i )
            {
                if ( IsSafeChar( (int) s[i] ) )
                    sb.Append( s[i] );
            }
 
            return sb.ToString();
        }
 
        public string ReadUTF8String()
        {
            if ( m_Index >= m_Size )
                return String.Empty;
 
            int count = 0;
            int index = m_Index;
 
            while ( index < m_Size && m_Data[index++] != 0 )
                ++count;
 
            index = 0;
 
            byte[] buffer = new byte[count];
            int value = 0;
 
            while ( m_Index < m_Size && (value = m_Data[m_Index++]) != 0 )
                buffer[index++] = (byte)value;
 
            return Utility.UTF8.GetString( buffer );
        }
 
        public string ReadString()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( m_Index < m_Size && (c = m_Data[m_Index++]) != 0 )
                sb.Append( (char)c );
 
            return sb.ToString();
        }
 
        public string ReadStringSafe()
        {
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( m_Index < m_Size && (c = m_Data[m_Index++]) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            return sb.ToString();
        }
 
        public string ReadUnicodeStringSafe( int fixedLength )
        {
            int bound = m_Index + (fixedLength << 1);
            int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < bound && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            m_Index = end;
 
            return sb.ToString();
        }
 
        public string ReadUnicodeString( int fixedLength )
        {
            int bound = m_Index + (fixedLength << 1);
            int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( (m_Index + 1) < bound && (c = ((m_Data[m_Index++] << 8) | m_Data[m_Index++])) != 0 )
                sb.Append( (char)c );
 
            m_Index = end;
 
            return sb.ToString();
        }
 
        public string ReadStringSafe( int fixedLength )
        {
            int bound = m_Index + fixedLength;
            int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( m_Index < bound && (c = m_Data[m_Index++]) != 0 )
            {
                if ( IsSafeChar( c ) )
                    sb.Append( (char)c );
            }
 
            m_Index = end;
 
            return sb.ToString();
        }
 
        public string ReadString( int fixedLength )
        {
            int bound = m_Index + fixedLength;
            int end   = bound;
 
            if ( bound > m_Size )
                bound = m_Size;
 
            StringBuilder sb = new StringBuilder();
 
            int c;
 
            while ( m_Index < bound && (c = m_Data[m_Index++]) != 0 )
                sb.Append( (char)c );
 
            m_Index = end;
 
            return sb.ToString();
        }
    }
}
1
 Аватар для Игрок_со_Смерть
37 / 37 / 6
Регистрация: 06.01.2013
Сообщений: 195
06.01.2013, 19:15  [ТС]
Спасибо за еще 1 код =) +1 в карму =)

В общем нашел так сказать оптимальный вариант, пока устраивает, если нужно то юзайте =)
Сам класс
Ну а тут пример его использования
А тут проект полностью

ЗЫ: Если не секрет что за приложение пишешь?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.01.2013, 19:15
Помогаю со студенческими работами здесь

Распарсить ассоциативный массив и добавить его в БД
Всем привет. Надеюсь на вашу помощь. AJAXом из JavaScript я передаю в php строку JSON, которую декодирую в ассоциативный массив. Который...

Progressbar или его аналоги
Доброго времени суток ув.Форумчане! Имееться код который загружает файлы на FTP, обычный ftp_put. Работает все отлично закачивает и т.п....

Что легче обрабатывать, массив или объект (ассоциативный массив)?
вопрос такой сейчас мне надо узнать что легче обрабатывать массив или объект? или &quot;что короче?&quot;

Ассоциативный массив как его перевести в порядок
Вот есть такой вот массив Подскажите как сделать что бы он выводилься вот так вот Данил Круто 25-06-2013 И скажите как...

Бесплатный reflector или его аналоги
Читаю книгу 2010 года троелсена, в ней пишется что reflector бесплатен, захожу по ссылке он платный, я так понимаю за это время его платным...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru