0

im working on a project that is like a chatroom nad all clients should connect to server. but im using tcp and i dont want to use multicasting and i want to server send a message to certain specefic client.

i wrote my code for one client at it works well but i dont know how to make it for more clients.

in my coding i used code like below:

ipAdd = ipHostInfo.AddressList[0];

i know array number 0 is the server and my own machine.

are array number 2 3 and... other clints that connected to server by order they connected or....?

maybe you say its a duplicate question but i really found no good answer on internet. this is the code i tried for my server and worked well for just one client. thanks a lot.

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;
using System.Threading;

namespace Server_Environment
{
    public partial class server_form : Form
    {
        public server_form()
        {
            InitializeComponent();
        }

        Socket listner;
        Socket handler;
        IPHostEntry ipHostInfo;
        IPAddress ipAdd;
        IPEndPoint localEndPoint;

        const int maxClient = 10;

        Thread thr1;
        Thread thr2;

        string data;

        byte[] msg;

        private delegate void setDisplay(string Text);
        private delegate void EnableTrue(bool b);

        private void Connection()
        {

            try
            {
                lblInitText("Waiting...");
                ipHostInfo = Dns.Resolve(Dns.GetHostName());
                ipAdd = ipHostInfo.AddressList[0];
                localEndPoint = new IPEndPoint(ipAdd, 1369);
                listner.Bind(localEndPoint);
                listner.Listen(maxClient);

                thr1 = new Thread(new ThreadStart(AcceptInit));
                thr1.Start();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AcceptInit()
        {
            try
            {
                handler = listner.Accept();
                thr2 = new Thread(new ThreadStart(DataReceiving));
                thr2.Start();

                lblInitText("connected");
                EnableAfterConnect(true);
                System.Media.SystemSounds.Exclamation.Play();


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DataReceiving()
        {
            try
            {
                byte[] bytes = new byte[1000];
                int byteRec;

                while (true)
                {
                    while (true)
                    {
                        byteRec = handler.Receive(bytes);
                        if (byteRec > 0)
                        {
                            data = System.Text.Encoding.UTF8.GetString(bytes, 0, byteRec);
                            break;
                        }
                    }

                    LastMessage(data);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LastMessage(string str)
        {
            try
            {
                if (lstchat.InvokeRequired == true)
                {
                    setDisplay d = new setDisplay(lastmessage);
                    this.Invoke(d, new object[] { str });
                }
                else
                {
                    lstchat.Items.Add("Client: " + str);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void lblInitText(string lblText)
        {
            if (lblstatus.InvokeRequired == true)
            {
                setDisplay dp = new setDisplay(lblInitText);
                this.Invoke(dp, new object[] { lblText });
            }
            else
            {
                lblstatus.Text = lblText;
            }
        }

        private void EnableAfterConnect(bool b)
        {
            if (txtmessage.InvokeRequired == true)
            {
                EnableTrue et = new EnableTrue(EnableAfterConnect);
                this.Invoke(et, new object[] { b });

            }
            else
            {
                txtmessage.Enabled = b;
            }
            //----------
            if (btnsend.InvokeRequired == true)
            {
                EnableTrue et = new EnableTrue(EnableAfterConnect);
                this.Invoke(et, new object[] { b });
            }
            else
            {
                btnsend.Enabled = b;
            }
            //----------
            if (lstchat.InvokeRequired == true)
            {
                EnableTrue et = new EnableTrue(EnableAfterConnect);
                this.Invoke(et, new object[] { b });
            }
            else
            {
                lstchat.Enabled = b;
            }
        }

        private void lastmessage(string str)
        {
            try
            {
                if (lstchat.InvokeRequired == true)
                {
                    setDisplay dp = new setDisplay(lastmessage);
                    this.Invoke(dp, new object[] { str });
                }
                else
                {
                    lstchat.Items.Add("Client: " + str);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void server_form_Load(object sender, EventArgs e)
        {
            IPHostEntry myHostInfo = Dns.Resolve(Dns.GetHostName());
            listner = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            lstchat.Enabled = false;
            txtmessage.Enabled = false;
            btnsend.Enabled = false;
            Connection();
        }

        private void server_form_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            try
            {
                handler.Shutdown(SocketShutdown.Both);
                listner.Shutdown(SocketShutdown.Both);
                thr1.Abort();
                thr2.Abort();
            }
            catch
            {
            }
            Environment.Exit(0);
        }

        private void btnsend_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtmessage.Text != "")
                {
                    msg = System.Text.Encoding.UTF8.GetBytes(txtmessage.Text);
                    handler.Send(msg);
                    lstchat.Items.Add("My: " + txtmessage.Text);
                    txtmessage.Text = "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtmessage_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnsend_Click(null,null);
        }
    }
}
virtouso
  • 549
  • 11
  • 30

1 Answers1

1

Some suggestions,

If you think about an existing scenario, when we chat we specifically know who we chat with. So if you want your app to have one-to-one communication do something like mapping "user names" to thread ID's handling each client in server. Then for each message send message with specific "User Name" so at server you can identify which thread to forward that message.

Remember You may dynamically create threads to handle more clients and also have checks for "Online clients" [Which could be a future implementation]

Relevant Info :

Getting the thread ID from a thread [Thread ID]

http://www.dotnetperls.com/hashtable [Something to store them]

P.S- First try to handle multiple clients with multi-cast using thread for each newly connected client. User arrays to store Thread ID and stuff and listen to every client using while loops. You may need Locks here to avoid race conditions.

http://www.dotnetperls.com/lock [Learn about locks]

Community
  • 1
  • 1
Kavindu Dodanduwa
  • 12,193
  • 3
  • 33
  • 46