Advertisement

how to specify clients on server

Started by December 08, 2014 12:20 PM
0 comments, last by hplus0603 9 years, 11 months ago

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);
        }
    }
}
When a client connects, put that connection (socket) into a map/hash table/other container.
When a client disconnects (or you get a write error to that client,) remove it from the map/table/container.
Each time you want to send a message to all clients, you have to iterate over the currently connected clients, and send the same message to each of them.
With TCP, there is no other way -- you have to send the same message many times (one per client.)
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement