Here is my updated code which is used to established a multiple connection and send data to device/client from server but my server does not receive a data from client, how to solve this issue please help me to solve this issue.
What I have tried:
Below code is my updated code from single connection to multiple connection. When I select a client from the list of connected device my server send the data to client easily but my server does not receive a data from client.
Code:
This section of code is established a multiple connection with device
private void btnstart_Click(object sender, EventArgs e)
{
string Systemip = getlocalip();
txtinfo.Text = "Server IP:" + Systemip + Environment.NewLine;
var portno = Int32.Parse("8010");
String a = "";
IPAddress ip = IPAddress.Parse(Systemip);
server = new TcpListener(ip, portno);
server.Start();
txtinfo.AppendText("Server started waiting for client.............." + Environment.NewLine);
counter = 0;
f = new Form1();
Thread newone = new Thread(loop);
newone.Start();
}
public delegate void messageone();
public void mess()
{
richtxtbddata.AppendText(counter + "clien connected" + Environment.NewLine);
richtxtbddata.AppendText("The client is from IP address: " + ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString() + Environment.NewLine);
listBox1.Items.Add(counter);
}
public void loop(object obj)
{
connectobj = new List<Multipleconnect>();
while (true)
{
counter++;
socketforclient = server.AcceptSocket();
connectobj.Add(new Multipleconnect
{
objectno = counter,
Skt = socketforclient,
nstream = new NetworkStream(socketforclient),
ip = ((IPEndPoint)socketforclient.RemoteEndPoint).Address.ToString()
});
richtxtbddata.Invoke(new messageone(mess));
Thread UserThread = new Thread(new ThreadStart(() => f.User(socketforclient)));
UserThread.Start();
}
}
public void User(Socket client)
{
while (true)
{
try
{
byte[] msg = new byte[1024];
int size = client.Receive(msg);
client.Send(msg, 0, size, SocketFlags.None);
}
catch (Exception ex)
{
txtinfo.Text = "Divice Disconnected";
}
}
}
This code for sending and receiving data. server send data to client successfully but this server does not receive a data from client.
private void btnsend_Click(object sender, EventArgs e)
{
isNew = true;
if (servermsg.Text != "") {
ns = new NetworkStream(socketforclient);
StreamWriter writer = new StreamWriter(ns);
writer.WriteLine(servermsg.Text + Environment.NewLine);
txtinfo.AppendText("Server:" + servermsg.Text + Environment.NewLine);
writer.Flush();
writer.Close();
}
ns = new NetworkStream(socketforclient);
StreamReader sr = new StreamReader(ns);
string myCompleteMessage = string.Empty;
if (ns.DataAvailable)
{
myReadBuffer = new byte[2048];
datafinal = new double[1];
myCompleteMessage = Encoding.ASCII.GetString(myReadBuffer, 0, readbytes);
}
if (myCompleteMessage != "")
{
txtinfo.AppendText("Client:" + myCompleteMessage + Environment.NewLine + Environment.NewLine);
}
}