Page 140 - CSharp/C#
P. 140

catch { }
                     }
                     SetupForReceiveing();
                    }
                }

                private void SetupForReceiveing()
                {
                   // View Client Class bottom of Client Example
                    Client.SetClient(_connectingSocket);
                    Client.StartReceiving();
                }


        Sending a message to the server


        So now we have an almost finish or Socket application. The only thing that we don't have jet is a
        Class for sending a message to the server.


         public class SendPacket
         {
             private Socket _sendSocked;

             public SendPacket(Socket sendSocket)
             {
                 _sendSocked = sendSocket;
             }

             public void Send(string data)
             {
                 try
                 {
                     /* what hapends here:
                          1. Create a list of bytes
                          2. Add the length of the string to the list.
                             So if this message arrives at the server we can easily read the length of
         the coming message.
                          3. Add the message(string) bytes
                     */

                     var fullPacket = new List<byte>();
                     fullPacket.AddRange(BitConverter.GetBytes(data.Length));
                     fullPacket.AddRange(Encoding.Default.GetBytes(data));

                     /* Send the message to the server we are currently connected to.
                     Or package stucture is {length of data 4 bytes (int32), actual data}*/
                     _sendSocked.Send(fullPacket.ToArray());
                 }
                 catch (Exception ex)
                 {
                     throw new Exception();
                 }
             }


        Finaly crate two buttons one for connect and the other for sending a message:


             private void ConnectClick(object sender, EventArgs e)
             {
                 Connector tpp = new Connector();



        https://riptutorial.com/                                                                               86
   135   136   137   138   139   140   141   142   143   144   145