0

I recently made this Server and Client with code I found on CodeProject.com. I can send data from the client to the server once, but after that, none of the data I send is acknowledged. Is there a loop I need to implement somewhere? The code is below:

    string hi;
    Socket sListener;
    Socket handler;
    Socket senderSocket;

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        IPHostEntry ipHost = Dns.GetHostEntry("localhost");
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
        sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
        sListener.Bind(ipEndPoint);
        sListener.Listen(10);
        AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
        sListener.BeginAccept(aCallback, sListener); 
    }

    private void AcceptCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        handler = listener.EndAccept(ar);
        Byte[] buffer = new Byte[1024];
        handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), handler);
        hi = Encoding.Unicode.GetString(buffer);
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        Socket listener = (Socket)ar.AsyncState;
        int endreceive = listener.EndReceive(ar);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        IPHostEntry ipHost = Dns.GetHostEntry("localhost");
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
        senderSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        senderSocket.Connect(ipEndPoint);
        byte[] msg = Encoding.Unicode.GetBytes(textBox2.Text);
        senderSocket.Send(msg); 
    }

    private void button3_Click(object sender, EventArgs e)
    {
        textBox1.Text = hi;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        byte[] msg = Encoding.Unicode.GetBytes("whatuphello");
        senderSocket.Send(msg);
    }
Nik Tedig
  • 453
  • 2
  • 6
  • https://msdn.microsoft.com/ru-ru/library/5bb431f9(v=vs.110).aspx might be usefull. And it`s better to create a server as a separate console app. – Vladimir Jun 29 '17 at 12:34

1 Answers1

0

When using the async BeginReceive method, you should also call the EndReceive. Here is the link to a similiar question with examples: C# Socket.BeginReceive/EndReceive

MaxP
  • 1
  • 1