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()" )?