0

I need to send and recive informations between two applications:

Host:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace DATA_SENDER_HOST
{
    public partial class Form1 : Form
    {
        static Socket sck;
        static byte[] Buffer { get; set; }
        Socket accepted;


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(0, 1234));
            sck.Listen(100);

            accepted = sck.Accept();
            Buffer = new byte[accepted.SendBufferSize];
            int bytesRead = accepted.Receive(Buffer);
            byte[] formatted = new byte[bytesRead];
            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string strData = Encoding.ASCII.GetString(formatted);
            if (strData == "1")
                panel1.BackColor = Color.Red;
            else if (strData == "2")
                panel1.BackColor = Color.Blue;
            sck.Close();
            accepted.Close();


        }
    }
}

Client:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace CLIENT
{
    public partial class Form1 : Form
    {
        static Socket sck;
        IPEndPoint localEndPoint;

        public Form1()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            sck.Connect(localEndPoint);
            string text = "1";
            byte[] data = Encoding.ASCII.GetBytes(text);
            sck.Send(data);

            sck.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
            sck.Connect(localEndPoint);
            string text = "2";
            byte[] data = Encoding.ASCII.GetBytes(text);
            sck.Send(data);

            sck.Close();
        }
    }
}

But in this case the host has to wait the data from the client;
My question is: how can I detect when client sends something without waiting(for waiting I mean "sck.Listen(100)" before "accepted = sck.Accept()" )?

CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
adrianoBP
  • 187
  • 6
  • 19
  • 2
    You might consider using `TcpClient` instead of a raw socket, and then you can make use of the [`NetworkStream`](https://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream(v=vs.110).aspx)'s various async methods. – CodingGorilla Apr 07 '16 at 19:14
  • And also, [length- and header-prefixing!](http://stackoverflow.com/questions/35233852/tcp-client-to-server-communication/35240061#35240061) – Visual Vincent Apr 07 '16 at 19:16

1 Answers1

1

The traditional way of doing this is to perform the Listen() in another thread in an infinite loop (if you're trying to build a server with infinite connections), then fire code whenever the listen gets triggered.

So something like this:

private void button1_Click(object sender, EventArgs e)
{

    sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    sck.Bind(new IPEndPoint(0, 1234));

    System.Threading.Thread T = new System.Threading.Thread((new System.Threading.ThreadStart(Listener)));

    T.Start();
}

private void Listener()
{
    sck.Listen(100);
    accepted = sck.Accept();
    Buffer = new byte[accepted.SendBufferSize];
    int bytesRead = accepted.Receive(Buffer);
    byte[] formatted = new byte[bytesRead];
    for (int i = 0; i < bytesRead; i++)
    {
        formatted[i] = Buffer[i];
    }
    string strData = Encoding.ASCII.GetString(formatted);
    panel1.Invoke((MethodInvoker)delegate
    {
        if (strData == "1")
            panel1.BackColor = Color.Red;
        else if (strData == "2")
            panel1.BackColor = Color.Blue;
    });
    sck.Close();
    accepted.Close();
}

If you want to make it infinitely wait for sockets (like most use cases of this kind of thing) you can put an infinite loop inside of Listener() function.

Hope this helps.

Jrud
  • 1,004
  • 9
  • 25