title: sending message using socket in c# not working
body: <p>I created a Socket server that accept client using websocket i'm trying to make a chat service but i'm stuck in two thing:</p>
  
  <p>1.i'm able to send msg from the browser to the server but not vice versa.</p>
  
  <p>2.once i write in the console and hit enter the connection is closed and i get disconnected message</p>
  
  <p>here is my code :</p>
  
  <p><strong>SERVER</strong></p>
  
  <pre><code> using System;
   using System.Net.Sockets;
   using System.Net;
   using System.Security.Cryptography;
   using System.Threading;
   using System.Text;
   using System.IO;
  
    namespace ConsoleApplication1
    {
  class Program
  {
      static Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
      static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  
      static void Main(string[] args)
      {
          serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080));
          serverSocket.Listen(128);
          serverSocket.BeginAccept(null, 0, OnAccept, null);
          Console.ReadLine();
      }
  
      private static void OnAccept(IAsyncResult result)
      {
  
          byte[] buffer = new byte[1024];
          try
          {
              Socket client = null;
              string headerResponse = "";
              if (serverSocket != null &amp;&amp; serverSocket.IsBound)
              {
  
                  client = serverSocket.EndAccept(result);
                  int i = client.Receive(buffer);
                  headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
                  // write received data to the console
                  Console.WriteLine(headerResponse);
  
              }
              if (client != null)
              {
  
                  //Console.WriteLine("Connected and waiting for a client msg");
                  /* Handshaking and managing ClientSocket */
  
                  var key = headerResponse.Replace("ey:", "`")
                            .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                            .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                            .Trim();
  
                  // key should now equal dGhlIHNhbXBsZSBub25jZQ==
                  var test1 = AcceptKey(ref key);
  
                  var newLine = "\r\n";
  
                  var response = "HTTP/1.1 101 Switching Protocols" + newLine
                       + "Upgrade: websocket" + newLine
                       + "Connection: Upgrade" + newLine
                       + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                      //+ "Sec-WebSocket-Protocol: chat, superchat" + newLine
                      //+ "Sec-WebSocket-Version: 13" + newLine
                       ;
  
  
                  client.Send(System.Text.Encoding.UTF8.GetBytes(response));
  
  
                  int received = ReceiveMsg(client);
  
                  // once the message is received decode it in different formats
                  Console.WriteLine(Convert.ToString(buffer).Substring(0, received));
  
                  Console.WriteLine("Type any word to send to the client");
                  Console.ReadLine();
                  int sent = client.Send(buffer, buffer.Length, SocketFlags.None);
                  Console.WriteLine("Sent {0} bytes.", sent); //the sent buffer is not displaying on browser
                  Console.ReadLine(); //here the connection is closed 
              }
          }
          catch (SocketException exception)
          {
              throw exception;
          }
          finally
          {
              if (serverSocket != null &amp;&amp; serverSocket.IsBound)
              {
                  serverSocket.BeginAccept(null, 0, OnAccept, null);
              }
          }
      }
  
  
      public static int ReceiveMsg(Socket server )
      {
          byte[] msg = Encoding.UTF8.GetBytes("This is a test");
          byte[] bytes = new byte[256];
          try
          {
              // Blocks until send returns. 
              int i = server.Send(msg);
              Console.WriteLine("Sent {0} bytes.", i);
  
              // Get reply from the server.
              i = server.Receive(bytes);
              ASCIIEncoding encoder = new ASCIIEncoding();
              Console.WriteLine(encoder.GetString(bytes, 0, bytes.Length));
          }
          catch (SocketException e)
          {
              Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
              return (e.ErrorCode);
          }
          return 0;
      }
  
      public static T[] SubArray&lt;T&gt;(T[] data, int index, int length)
      {
          T[] result = new T[length];
          Array.Copy(data, index, result, 0, length);
          return result;
      }
  
      private static string AcceptKey(ref string key)
      {
          string longKey = key + guid;
          byte[] hashBytes = ComputeHash(longKey);
          return Convert.ToBase64String(hashBytes);
      }
  
      static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
      private static byte[] ComputeHash(string str)
      {
          return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
      }
     }
   }
  </code></pre>
  
  <p><strong>CLIENT</strong></p>
  
  <pre><code>&lt;!DOCTYPE HTML&gt;
   &lt;html lang = "en"&gt;
   &lt;head&gt;
    &lt;title&gt;WebSocket Test&lt;/title&gt;
     &lt;style type = "text/css"&gt;
      h1 {
       text-align: center;
     }
       .error {
         color: red;
     } 
      .response {
        color: blue;
     }
     fieldset {
       width: 80%;
        margin: auto;
    text-align: center;
    -moz-box-shadow: 10px 10px 10px #000000;
     -webkit-box-shadow: 10px 10px 10px #000000;
   }
    #output {
  font-family: monospace;
  width: 80%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 1em;
  background-color: #eeeeee;
  padding: 1em;
  border: 5px groove #cccccc;
  -moz-border-radius: 15px;
  -webkit-border-radius: 15px;
  -moz-box-shadow: 10px 10px 10px #000000;
  -webkit-box-shadow: 10px 10px 10px #000000;
     } 
    &lt;/style&gt;
     &lt;script language="javascript" type="text/javascript"&gt;
    var output;
    var websocket;
    function init() {
        output = document.getElementById("output");
    } // end init
    function connect() {
        //open socket
        if ("WebSocket" in window) {
            websocket = new WebSocket("ws://localhost:8080/server2");
            //note this server does nothing but echo what was passed
            //use a more elaborate server for more interesting behavior
  
            output.innerHTML = "connecting...";
  
            //attach event handlers
            websocket.onopen = onOpen;
            websocket.onclose = onClose;
            websocket.onmessage = onMessage;
  
            websocket.onerror = onError;
        } else {
            alert("WebSockets not supported on your browser.");
        } // end if
     } // end connect
     function onOpen(evt) {
        //called as soon as a connection is opened
        output.innerHTML = "&lt;p&gt;CONNECTED TO SERVER&lt;/p&gt;";
    } // end onOpen
    function onClose(evt) {
        //called when connection is severed
        output.innerHTML += "&lt;p&gt;DISCONNECTED&lt;/p&gt;"+evt.data;
    } // end onClose;
    function onMessage(evt) {
        //called on receipt of message
        alert("msg received");
        output.innerHTML += "&lt;p class = 'response'&gt;RESPONSE: "
    + evt.data + "&lt;/p&gt;";
    } // end onMessage
    function onError(evt) {
        //called on error
        output.innerHTML += "&lt;p class = 'error'&gt;ERROR: "
    + evt.data + "&lt;/p&gt;";
    } // end onError
    function sendMessage() {
        //get message from text field
        txtMessage = document.getElementById("txtMessage");
        message = txtMessage.value;
        //pass message to server
        websocket.send(message);
        output.innerHTML += "&lt;p&gt;MESSAGE SENT: " + message + "&lt;/p&gt;";
    } // end sendMessage
  
     &lt;/script&gt;
  &lt;/head&gt;
      &lt;body onload = "init()"&gt;
     &lt;h1&gt;Web Socket Echo Chamber&lt;/h1&gt;
     &lt;form action = ""&gt;
      &lt;fieldset&gt;
    &lt;button type = "button" onclick = "connect()"&gt;connect to server&lt;/button&gt;
    &lt;label for = "txtMessage"&gt;
      &lt;input type = "text"  id = "txtMessage" value = "HTML5 Quick Reference For Dummies" /&gt;
    &lt;/label&gt;
    &lt;button type = "button" onclick = "sendMessage()"&gt;send message&lt;/button&gt;
    &lt;button type = "button" onclick = "websocket.close()"&gt;disconnect&lt;/button&gt;
  &lt;/fieldset&gt;
     &lt;/form&gt;
      &lt;div id="output"&gt;Click 'connect' button to connect&lt;/div&gt;
   &lt;/body&gt;
     &lt;/html&gt;
  </code></pre>
  
  <p>Any Idea ?? </p>