Click here to Skip to main content
       

C#

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page  Show 
QuestionHow to call a "Windows Form Application" in a "Windows Service"?memberDaKhucBuon22-Jan-13 1:40 
AnswerRe: How to call a "Windows Form Application" in a "Windows Service"?memberPIEBALDconsult22-Jan-13 2:21 
AnswerRe: How to call a "Windows Form Application" in a "Windows Service"?mvpDave Kreskowiak22-Jan-13 2:27 
AnswerRe: How to call a "Windows Form Application" in a "Windows Service"?memberCollin Jasnoch22-Jan-13 3:34 
GeneralRe: How to call a "Windows Form Application" in a "Windows Service"?memberDaKhucBuon22-Jan-13 13:56 
GeneralRe: How to call a "Windows Form Application" in a "Windows Service"?memberPIEBALDconsult22-Jan-13 15:50 
AnswerRe: How to call a "Windows Form Application" in a "Windows Service"?memberDaKhucBuon23-Jan-13 15:59 
Question(solved) grab selected text from anywhere [modified]membermsickel21-Jan-13 23:34 
AnswerRe: grab selected text from anywheremvpRichard MacCutchan21-Jan-13 23:59 
AnswerRe: grab selected text from anywherememberSledgeHammer0122-Jan-13 4:53 
AnswerRe: grab selected text from anywherememberRavi Bhavnani22-Jan-13 10:20 
GeneralRe: grab selected text from anywheremembermsickel23-Jan-13 0:58 
QuestionSocket chat client & Server helpmemberDioblos21-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
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
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;
            }
        }
 
    }
}
 

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 helpmvpEddy Vluggen21-Jan-13 13:00 
GeneralRe: Socket chat client & Server helpmemberDioblos21-Jan-13 13:24 
GeneralRe: Socket chat client & Server helpmvpEddy Vluggen21-Jan-13 13:37 
GeneralRe: Socket chat client & Server helpmemberDioblos21-Jan-13 14:30 
AnswerRe: Socket chat client & Server helpmvpEddy Vluggen21-Jan-13 14:42 
GeneralRe: Socket chat client & Server helpmemberDioblos21-Jan-13 14:49 
GeneralRe: Socket chat client & Server helpmvpEddy Vluggen21-Jan-13 14:56 
GeneralRe: Socket chat client & Server helpmemberDioblos21-Jan-13 15:01 
GeneralRe: Socket chat client & Server helpmvpDave Kreskowiak21-Jan-13 15:58 
AnswerRe: Socket chat client & Server help [modified]memberpt140121-Jan-13 19:55 
AnswerRe: Socket chat client & Server helpmemberJ4amieC21-Jan-13 21:47 
GeneralRe: Socket chat client & Server helpmemberDioblos22-Jan-13 4:54 
GeneralRe: Socket chat client & Server helpmemberJ4amieC22-Jan-13 5:25 
AnswerRe: Socket chat client & Server helpmvpRichard MacCutchan21-Jan-13 22:25 
AnswerRe: Socket chat client & Server helpmemberpt140122-Jan-13 3:26 
QuestionC# 2010 objectmemberdcof21-Jan-13 8:57 
AnswerRe: C# 2010 objectmemberjibesh21-Jan-13 12:00 
AnswerRe: C# 2010 objectmvpEddy Vluggen21-Jan-13 13:01 
AnswerRe: C# 2010 objectmemberFreak3021-Jan-13 21:53 
GeneralC#.net with postGismembertashee21-Jan-13 3:47 
GeneralRe: C#.net with postGismvpEddy Vluggen21-Jan-13 13:03 
QuestionHow to handle Image/Data from Centralized SQL ServermemberHema Bairavan21-Jan-13 0:46 
AnswerRe: How to handle Image/Data from Centralized SQL ServermvpEddy Vluggen21-Jan-13 1:21 
GeneralRe: How to handle Image/Data from Centralized SQL ServermemberHema Bairavan21-Jan-13 5:59 
GeneralRe: How to handle Image/Data from Centralized SQL ServerprotectorPete O'Hanlon21-Jan-13 6:06 
GeneralRe: How to handle Image/Data from Centralized SQL ServermvpEddy Vluggen21-Jan-13 6:10 
AnswerRe: How to handle Image/Data from Centralized SQL ServermemberV.21-Jan-13 1:32 
GeneralRe: How to handle Image/Data from Centralized SQL ServermemberHema Bairavan21-Jan-13 6:08 
GeneralRe: How to handle Image/Data from Centralized SQL ServermemberV.21-Jan-13 6:15 
AnswerRe: How to handle Image/Data from Centralized SQL Servermemberjschell21-Jan-13 8:05 
SuggestionRe: How to handle Image/Data from Centralized SQL ServermemberHema Bairavan21-Jan-13 19:14 
Questionfingerprint recognitionmemberyinyin8421-Jan-13 0:37 
AnswerRe: fingerprint recognitionmvpAbhinav S21-Jan-13 0:59 
GeneralRe: fingerprint recognitionmemberyinyin8425-Jan-13 18:29 
AnswerRe: fingerprint recognitionmvpRahul Rajat Singh21-Jan-13 1:05 
GeneralRe: fingerprint recognitionmemberyinyin8425-Jan-13 18:28 
AnswerRe: fingerprint recognitionmemberSivaraman Dhamodharan21-Jan-13 1:26 

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


Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 18 Jun 2013
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid