Click here to Skip to main content
15,885,216 members
Home / Discussions / C#
   

C#

 
GeneralRe: How to call a "Windows Form Application" in a "Windows Service"? Pin
PIEBALDconsult22-Jan-13 15:50
mvePIEBALDconsult22-Jan-13 15:50 
AnswerRe: How to call a "Windows Form Application" in a "Windows Service"? Pin
DaKhucBuon23-Jan-13 15:59
DaKhucBuon23-Jan-13 15:59 
Question(solved) grab selected text from anywhere Pin
msickel21-Jan-13 23:34
msickel21-Jan-13 23:34 
AnswerRe: grab selected text from anywhere Pin
Richard MacCutchan21-Jan-13 23:59
mveRichard MacCutchan21-Jan-13 23:59 
AnswerRe: grab selected text from anywhere Pin
SledgeHammer0122-Jan-13 4:53
SledgeHammer0122-Jan-13 4:53 
AnswerRe: grab selected text from anywhere Pin
Ravi Bhavnani22-Jan-13 10:20
professionalRavi Bhavnani22-Jan-13 10:20 
GeneralRe: grab selected text from anywhere Pin
msickel23-Jan-13 0:58
msickel23-Jan-13 0:58 
QuestionSocket chat client & Server help Pin
Dioblos21-Jan-13 11:52
Dioblos21-Jan-13 11:52 
Hey I have problem running my code, the client seems to not connect with the server, hope someone can help me I have been trying to fix this out for 5 days now.

2 Projects. sockerServer contain a client class and socketClient with chatroom GUI

sockerServer
C#
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.Net;

namespace SocketServer
{
    public delegate void LogUpdater(string msg);

    public partial class Form1 : Form
    {
        ////Private Variables
       
        private Thread serverThread;
        private TcpListener serverListener;
        private Hashtable clientTable;

        
        public Form1()
        {
            InitializeComponent();
            clientTable = new Hashtable();
            //Start a thread on the startListen method
            serverThread = new Thread(new ThreadStart(startListen));
            serverThread.Start();
            AddLog("Socket Server Started");
        }
        public void startListen()
        {
            try
            {
                //Start the tcpListner
                serverListener = new TcpListener(IPAddress.Any, 5151);
                serverListener.Start();
                do
                {
                    //Create a new class when a new Chat Client connects
                    Client newClient = new Client(serverListener.AcceptTcpClient());
                    //Attach the Delegates
                    newClient.Disconnected += new DisconnectDelegate(OnDisconnected);
                    newClient.Connected += new ConnectDelegate(this.OnConnected);
                    newClient.MessageReceived += new MessageDelegate(OnMessageReceived);
                    //Connect to the clients
                    newClient.Connect();
                }
                while (true);
            }
            catch
            {
                serverListener.Stop();
            }
        }
        //EvntsHandler fo the Connected event
        public void OnConnected(object sender, EventArgs e)
        {
            //Get the client that raised the vent
            Client temp = (Client)sender;
            //Add the client to the Hashtable
            clientTable.Add(temp.ID, temp);
            Client tempClient;
            AddLog("Client Connected:" + temp.UserName);
            //loop through each client and announce the 
            //client connected
            foreach (DictionaryEntry d in clientTable)
            {
                tempClient = (Client)d.Value;
                tempClient.Send(tempClient.ID + "@Connected@" + temp.UserName);
            }
        }

        public void OnDisconnected(object sender, EventArgs e)
        {
            //Get the Client that raised the Event
            Client temp = (Client)sender;
            //If the Client exists in the Hashtable
            if (clientTable.ContainsKey(temp.ID))
            {
                AddLog("Client Disconnected:" + temp.UserName);
                //Remove the client from the hashtable
                clientTable.Remove(temp.ID);
                //Remove the client from the ClientList class
                ClientList.RemoveClient(temp.UserName, temp.ID);
                Client tempClient;
                //Announce to all the existing clients
                foreach (DictionaryEntry d in clientTable)
                {
                    tempClient = (Client)d.Value;
                    tempClient.Send(tempClient.ID + "@Disconnected@" + temp.UserName);
                }
            }
        }
        public void OnMessageReceived(object sender, MessageEventArgs e)
        {
            //Message sender client
            Client temp = (Client)sender;
            AddLog(temp.UserName + " :" + e.Message);
            Client tempClient;
            //Send the message to each client
            foreach (DictionaryEntry d in clientTable)
            {
                tempClient = (Client)d.Value;
                tempClient.Send(temp.UserName + " :" + e.Message);
            }
        }
        //Method to add the string to the server log
        public void AddLog(string msg)
        {
            logBox.Items.Add(msg);
        }

        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            serverListener.Stop();
        }
    }
}


The Class
C#
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServer
{
    public delegate void ConnectDelegate(object sender, EventArgs e);
    public delegate void DisconnectDelegate(object sender, EventArgs e);
    public delegate void MessageDelegate(object sender, MessageEventArgs e);

    public class MessageEventArgs : EventArgs
    {
        private string msg;
        public string Message
        {
            get
            {
                return this.msg;
            }
            set
            {
                this.msg = value;
            }
        }
    }

    public class Client
    {
        //Events Defination
        public event ConnectDelegate Connected;
        public event DisconnectDelegate Disconnected;
        public event MessageDelegate MessageReceived;
        //Some Variables
        private bool firstTime = true;
        private bool connected = false;
        private byte[] recByte = new byte[1024];
        private StringBuilder myBuilder = new StringBuilder();
        private TcpClient myClient;
        private string userName, clientID;

        public Client(TcpClient myClient)
        {
            this.myClient = myClient;
        }
        //Connect method used to connect to Client
        public void Connect()
        {

            //Assign a new Guid
            this.clientID = Guid.NewGuid().ToString();
            //Start Receiving the Messages
            AsyncCallback GetStreamMsgCallback = new AsyncCallback(GetStreamMsg);
            myClient.GetStream().BeginRead(recByte, 0, 1024, GetStreamMsgCallback, null);
        }

        public string UserName
        {
            get
            {
                return this.userName;
            }
        }

        public string ID
        {
            get
            {
                return this.clientID;
            }
        }

        public void GetStreamMsg(IAsyncResult ar)
        {
            int intCount;
            try
            {
                //Lock the Client Stream
                lock (myClient.GetStream())
                {
                    //Receive the Bytes
                    intCount = myClient.GetStream().EndRead(ar);
                }
                if (intCount < 1)
                {
                    //If a value less than 1 received that means that 
                    //client disconnected
                    myClient.Close();
                    //raise the Disconnected Event
                    if (Disconnected != null)
                    {
                        EventArgs e = new EventArgs();
                        Disconnected(this, e);
                    }
                }
                //Send the received message from processing
                BuildText(recByte, 0, intCount);
                if (!firstTime)
                {
                    //if its not the first time then restart the listen process
                    lock (myClient.GetStream())
                    {
                        AsyncCallback GetStreamMsgCallback = new AsyncCallback(GetStreamMsg);
                        myClient.GetStream().BeginRead(recByte, 0, 1024, GetStreamMsgCallback, null);
                    }
                }
            }
            catch
            {
                myClient.Close();
                if (Disconnected != null)
                {
                    EventArgs e = new EventArgs();
                    Disconnected(this, e);
                }
            }
        }

        public void Disconnect()
        {
            this.connected = false;
            myClient.Close();
        }
        //Method that takes the Usernam and does some processing
        public void CheckUserName(string userName)
        {
            if (userName.Length > 20)
            {
                Send("sorry@Username too long, enter a Username less than 20 Characters!!");
                Disconnect();
                return;
            }
            else if (userName.IndexOf("@") >= 0)
            {
                Send("sorry@Invalid Character in Username!!");
                Disconnect();
                return;
            }
            else if (!ClientList.AddClient(userName, this.clientID))
            {
                //Check if the username is duplicate
                Send("sorry@Duplicate Username, try another Username!!");
                Disconnect();
                return;
            }
            else
            {
                //If name is not duplicate then the client is connected
                this.connected = true;
                this.userName = userName;
                //Build the Usernames list and send it to the client
                StringBuilder userList = new StringBuilder();
                userList.Append(this.clientID);
                Hashtable clientTable = ClientList.GetList;
                foreach (DictionaryEntry d in clientTable)
                {
                    //Seperate the usernames by a '@'
                    userList.Append("@");
                    userList.Append(d.Value.ToString());
                }
                //Start the llistening
                lock (myClient.GetStream())
                {
                    AsyncCallback GetStreamMsgCallback = new AsyncCallback(GetStreamMsg);
                    myClient.GetStream().BeginRead(recByte, 0, 1024, GetStreamMsgCallback, null);
                }
                //Send the Userlist
                Send(userList.ToString());
                //Raise the Connected Event
                if (Connected != null)
                {
                    EventArgs e = new EventArgs();
                    Connected(this, e);
                }
            }
        }

        //Method to process the Messages
        public void BuildText(byte[] dataByte, int offset, int count)
        {

            for (int i = 0; i < count; i++)
            {
                //Check is a line terminator is encountered
                if (dataByte[i] == 13)
                {

                    if (firstTime)
                    {
                        //If first time then call the CheckUserName method
                        CheckUserName(myBuilder.ToString().Trim());
                        firstTime = false;
                    }
                    else if (MessageReceived != null && connected)
                    {
                        //Else raise the MessageReceived Event 
                        //and pass the message along
                        MessageEventArgs e = new MessageEventArgs();
                        e.Message = (myBuilder.ToString()).Trim();
                        MessageReceived(this, e);
                    }
                    //Clear the StringBuilder
                    myBuilder = new System.Text.StringBuilder();
                }
                else
                {
                    //Append the Byte to the StringBuilder
                    myBuilder.Append(Convert.ToChar(dataByte[i]));
                }
            }
        }

        //Method to send the message
        public void Send(string msg)
        {
            lock (myClient.GetStream())
            {
                System.IO.StreamWriter myWriter = new System.IO.StreamWriter(myClient.GetStream());
                myWriter.Write(msg);
                myWriter.Flush();
            }
        }
    }

    //Class to maintain the Userlist
    public class ClientList
    {
        private static Hashtable clientTable = new Hashtable();

        //Method to add a new user
        public static bool AddClient(string userName, string id)
        {
            lock (clientTable)
            {
                //If username exists return false
                if (clientTable.ContainsValue(userName))
                {
                    return false;
                }
                else
                {
                    //Or add the username to the list and return true
                    clientTable.Add(id, userName);
                    return true;
                }
            }
        }

        //Method to remove the user
        public static bool RemoveClient(string userName, string id)
        {
            lock (clientTable)
            {
                if (clientTable.ContainsValue(userName))
                {
                    clientTable.Remove(id);
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        //Property to get the Users list
        public static Hashtable GetList
        {
            get
            {
                return clientTable;
            }
        }

    }
}



C#
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Collections;


namespace SocketClient
{
    public delegate void displayMessage(string msg);

    public partial class Form1 : Form
    {
        //Some required Variables
        private string userID, userName;
        //Flag to check if this is the first communication with the server
        bool firstTime = true;
        private TcpClient chatClient;
        private byte[] recByte = new byte[1024];
        private StringBuilder myBuilder;
        public Form1()
        {
            InitializeComponent();
            myBuilder = new System.Text.StringBuilder();
        }
        //Method use to process incomming messages
        public void GetMsg(IAsyncResult ar)
        {
            int byteCount;
            try
            {
                //Get the number of Bytes received
                byteCount = (chatClient.GetStream()).EndRead(ar);
                //If bytes received is less than 1 it means
                //the server has disconnected
                if (byteCount < 1)
                {
                    //Close the socket
                    Disconnect();
                    MessageBox.Show("Disconnected!!");
                    return;
                }
                //Send the Server message for parsing
                BuildText(recByte, 0, byteCount);
                //Unless its the first time start Asynchronous Read
                //Again
                if (!firstTime)
                {
                    AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
                    (chatClient.GetStream()).BeginRead(recByte, 0, 1024, GetMsgCallback, this);
                }
            }
            catch (Exception ed)
            {
                Disconnect();
                MessageBox.Show("Exception Occured :" + ed.ToString());
            }
        }

        //Method to Process Server Response
        public void BuildText(byte[] dataByte, int offset, int count)
        {
            //Loop till the number of bytes received
            for (int i = offset; i < (count); i++)
            {
                //If a New Line character is met then
                //skip the loop cycle
                if (dataByte[i] == 10)
                    continue;
                //Add the Byte to the StringBuilder in Char format
                myBuilder.Append(Convert.ToChar(dataByte[i]));
            }
            char[] spliters = { '@' };
            //Check if this is the first message received
            if (firstTime)
            {
                //Split the string received at the occurance of '@'
                string[] tempString = myBuilder.ToString().Split(spliters);
                //If the Server sent 'sorry' that means there was some error
                //so we just disconnect the client
                if (tempString[0] == "sorry")
                {
                    object[] temp = { tempString[1] };
                    this.Invoke(new displayMessage(DisplayText), temp);
                    Disconnect();
                }
                else
                {
                    //Store the Client Guid 
                    this.userID = tempString[0];
                    //Loop through array of UserNames
                    for (int i = 1; i < tempString.Length; i++)
                    {
                        object[] temp = { tempString[i] };
                        //Invoke the AddUser method
                        //Since we are working on another thread rather than the primary 
                        //thread we have to use the Invoke method
                        //to call the method that will update the listbox
                        this.Invoke(new displayMessage(AddUser), temp);
                    }
                    //Reset the flag
                    firstTime = false;
                    //Start the listening process again 
                    AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
                    (chatClient.GetStream()).BeginRead(recByte, 0, 1024, GetMsgCallback, this);
                }

            }
            else
            {
                //Generally all other messages get passed here
                //Check if the Message starts with the ClientID
                //In which case we come to know that its a Server Command
                if (myBuilder.ToString().IndexOf(this.userID) >= 0)
                {
                    string[] tempString = myBuilder.ToString().Split(spliters);
                    //If its connected command then add the user to the ListBox
                    if (tempString[1] == "Connected")
                    {
                        object[] temp = { tempString[2] };
                        this.Invoke(new displayMessage(AddUser), temp);
                    }
                    else if (tempString[1] == "Disconnected")
                    {
                        //If its disconnected command then remove the 
                        //username from the list box
                        object[] temp = { tempString[2] };
                        this.Invoke(new displayMessage(RemoveUser), temp);
                    }
                }
                else
                {
                    //For regular messages append a Line terminator
                    myBuilder.Append("\r\n");
                    object[] temp = { myBuilder.ToString() };
                    //Invoke the DisplayText method
                    this.Invoke(new displayMessage(DisplayText), temp);
                }
            }
            //Empty the StringBuilder
            myBuilder = new System.Text.StringBuilder();
        }

        //Method to remove the user from the ListBox
        private void RemoveUser(string user)
        {
            if (userlistBox.Items.Contains(user))
                userlistBox.Items.Remove(user);
            //Display the left message
            DisplayText(user + " left chat\r\n");
        }

        //Method to Add a user to the ListBox
        private void AddUser(string user)
        {
            if (!userlistBox.Items.Contains(user))
                userlistBox.Items.Add(user);
            //If not for first time then display a connected message
            if (!firstTime)
                DisplayText(user + " joined chat\r\n");
        }
        //Method to send a message to the server
        public void SendText(string msg)
        {
            //Get a StreamWriter 
            System.IO.StreamWriter chatWriter = new System.IO.StreamWriter(chatClient.GetStream());
            chatWriter.WriteLine(msg);
            //Flush the stream
            chatWriter.Flush();
        }

        //Method to Display Text in the TextBox
        public void DisplayText(string msg)
        {
            msgViewBox.AppendText(msg);
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            if (sendBox.Text != "")
            {
                //Send Message
                SendText(sendBox.Text);
                sendBox.Text = "";
            }
        }
        private void Disconnect()
        {
            if (chatClient != null)
            {
                chatClient.Close();
                chatClient = null;
            }
            //Reset the Buttons and Variables
            userlistBox.Items.Clear();
            sendButton.Enabled = false;
            connectButton.Text = "Connect";
            usernameBox.Enabled = true;
            sendBox.Enabled = false;
            this.AcceptButton = connectButton;
            firstTime = true;
            userID = "";
        }

        private void connectButton_Click(object sender, EventArgs e)
        {

            //If user Cliked Connect
            if (connectButton.Text == "Connect" && usernameBox.Text != "")
            {
                try
                {
                    //Connect to server
                    chatClient = new TcpClient("localhost", 5151);
                    DisplayText("Connecting to Server ...\r\n");
                    //Start Reading
                    AsyncCallback GetMsgCallback = new AsyncCallback(GetMsg);
                    (chatClient.GetStream()).BeginRead(recByte, 0, 1024, GetMsgCallback, null);
                    //Send the UserName
                    SendText(usernameBox.Text);
                    this.userName = usernameBox.Text;
                    this.Text = "Chat Client :" + userName;
                    usernameBox.Text = "";
                    connectButton.Text = "Disconnect";
                    usernameBox.Enabled = false;
                    sendButton.Enabled = true;
                    sendBox.Enabled = true;
                    this.AcceptButton = sendButton;
                }
                catch
                {
                    Disconnect();
                    MessageBox.Show("Can't connect to Server...");
                }
            }
            else if (connectButton.Text == "Disconnect")
            {
                Disconnect();
            }

        }

    }
}

AnswerRe: Socket chat client & Server help Pin
Eddy Vluggen21-Jan-13 13:00
professionalEddy Vluggen21-Jan-13 13:00 
GeneralRe: Socket chat client & Server help Pin
Dioblos21-Jan-13 13:24
Dioblos21-Jan-13 13:24 
GeneralRe: Socket chat client & Server help Pin
Eddy Vluggen21-Jan-13 13:37
professionalEddy Vluggen21-Jan-13 13:37 
GeneralRe: Socket chat client & Server help Pin
Dioblos21-Jan-13 14:30
Dioblos21-Jan-13 14:30 
AnswerRe: Socket chat client & Server help Pin
Eddy Vluggen21-Jan-13 14:42
professionalEddy Vluggen21-Jan-13 14:42 
GeneralRe: Socket chat client & Server help Pin
Dioblos21-Jan-13 14:49
Dioblos21-Jan-13 14:49 
GeneralRe: Socket chat client & Server help Pin
Eddy Vluggen21-Jan-13 14:56
professionalEddy Vluggen21-Jan-13 14:56 
GeneralRe: Socket chat client & Server help Pin
Dioblos21-Jan-13 15:01
Dioblos21-Jan-13 15:01 
GeneralRe: Socket chat client & Server help Pin
Dave Kreskowiak21-Jan-13 15:58
mveDave Kreskowiak21-Jan-13 15:58 
AnswerRe: Socket chat client & Server help Pin
pt140121-Jan-13 19:55
pt140121-Jan-13 19:55 
AnswerRe: Socket chat client & Server help Pin
J4amieC21-Jan-13 21:47
J4amieC21-Jan-13 21:47 
GeneralRe: Socket chat client & Server help Pin
Dioblos22-Jan-13 4:54
Dioblos22-Jan-13 4:54 
GeneralRe: Socket chat client & Server help Pin
J4amieC22-Jan-13 5:25
J4amieC22-Jan-13 5:25 
AnswerRe: Socket chat client & Server help Pin
Richard MacCutchan21-Jan-13 22:25
mveRichard MacCutchan21-Jan-13 22:25 
AnswerRe: Socket chat client & Server help Pin
pt140122-Jan-13 3:26
pt140122-Jan-13 3:26 
QuestionC# 2010 object Pin
dcof21-Jan-13 8:57
dcof21-Jan-13 8:57 
AnswerRe: C# 2010 object Pin
Jibesh21-Jan-13 12:00
professionalJibesh21-Jan-13 12:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.