RSS Forums RSS

Socket Programming -- Help required

Please support our C# advertiser: DiscountASP.NET – 3 Months Free on C# Web Hosting
Thread Solved
Reply
Posts: 11
Reputation: smnadig is an unknown quantity at this point 
Solved Threads: 0
smnadig smnadig is offline Offline
Newbie Poster

Socket Programming -- Help required

  #1  
Dec 1st, 2008
Hi,

I am working on "Creating A Multiuser Chat Application" in C#. The code is generating an error --
"SocketException unhandled -- The requested address is not valid in its context" when it executes
listener.Start(); method.

Can somebody kindly help me resolving this?
Please find the code below for your reference. Thanks in Advance

Server:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;


namespace Server
{
    class Program
    {
        const int portNo = 500;
        static void Main(string[] args)
        {
            System.Net.IPAddress localAdd = System.Net.IPAddress.Parse("172.23.0.60");
            TcpListener listener = new TcpListener(localAdd, portNo);
            
            listener.Start();

            while (true)
            {
                ChatClient user = new ChatClient(listener.AcceptTcpClient());
            }

        }
    }
}

Client:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Collections;

namespace Server
{
    class ChatClient
    {
        //---contains a list of all the clients---
        public static Hashtable AllClients = new Hashtable();

        //---information about the client---
        private TcpClient _client;
        private string _clientIP;
        private string _clientNick;

        //---used for sending/receiving data---
        private byte[] data;

        //---is the nickname being sent?---
        private bool ReceiveNick = true;


        public ChatClient(TcpClient client)
        {
            _client = client;

            //---get the client IP address---
            _clientIP = client.Client.RemoteEndPoint.ToString();

            //---add the current client to the hash table---
            AllClients.Add(_clientIP, this);

            //---start reading data from the client in a separate thread---
            data = new byte[_client.ReceiveBufferSize];
            client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(_client.ReceiveBufferSize), ReceiveMessage, null);
        }

        public void ReceiveMessage(IAsyncResult ar)
        {
            //---read from client---
            int bytesRead;
            try
            {
                lock (_client.GetStream())
                {
                    bytesRead = _client.GetStream().EndRead(ar);
                }
                //---client has disconnected---
                if (bytesRead < 1)
                {
                    AllClients.Remove(_clientIP);
                    Broadcast(_clientNick + " has left the chat.");
                    return;
                }
                else
                {
                    //---get the message sent---
                    string messageReceived = System.Text.Encoding.ASCII.GetString(data, 0, bytesRead);

                    //---client is sending its nickname---
                    if (ReceiveNick)
                    {
                        _clientNick = messageReceived;

                        //---tell everyone client has entered the chat---
                        Broadcast(_clientNick + " has joined the chat.");
                        ReceiveNick = false;
                    }
                    else
                    {
                        //---broadcast the message to everyone---
                        Broadcast(_clientNick + ">" + messageReceived);
                    }
                }
                //---continue reading from client---
                lock (_client.GetStream())
                {
                    _client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(_client.ReceiveBufferSize), ReceiveMessage, null);
                }
            }
            catch (Exception ex)
            {
                AllClients.Remove(_clientIP);
                Broadcast(_clientNick + " has left the chat.");
            }
        }

        public void SendMessage(string message)
        {
            try
            {
                //---send the text---
                System.Net.Sockets.NetworkStream ns;
                lock (_client.GetStream())
                {
                    ns = _client.GetStream();
                }
                byte[] bytesToSend =
                System.Text.Encoding.ASCII.GetBytes(message);
                ns.Write(bytesToSend, 0, bytesToSend.Length);
                ns.Flush();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        public void Broadcast(string message)
        {
            //---log it locally---
            Console.WriteLine(message);
            foreach (DictionaryEntry c in AllClients)
            {
                //---broadcast message to all users---
                ((ChatClient)(c.Value)).SendMessage(
                message + Environment.NewLine);
            }
        }

    }
}
Thanks & Regards
AddThis Social Bookmark Button
Reply With Quote  
Posts: 1,734
Reputation: LizR has a spectacular aura about LizR has a spectacular aura about 
Solved Threads: 184
LizR LizR is offline Offline
Posting Virtuoso

Re: Socket Programming -- Help required

  #2  
Dec 1st, 2008
Sure thats your IP address and that you dont have a dynamic one? On changing your code to be my local IP and dropping the chat client part as it was a test, and putting in a simple receive, acknowledge and disconnect.
Did I just hear "You gotta help us, Doc. We've tried nothin' and we're all out of ideas" ? Is this you? Dont let this be you! I will put in as much effort as you seem to.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.



Views: 899 | Replies: 1 | Currently Viewing: 1 (0 members and 1 guests)

 

Thread Tools Display Modes
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 2:37 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC