2

Am new to socket programming and am creating a chat application.As like other applications whenever i press enter in a chat window it should send the chat to a particular user.Am maintaining a DB for all users along with their IPAddresses.So whenever i select a user for sending chat it should send to the corresponding IPAddress.As of now am trying to send chat to my own machine(so i hard coded the IPAddress of my machine).But am getting an exception when i try to send my code to my IPAddress.Can anyone please help me out.

My code for socket programming is this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Net.Sockets;

namespace Ping
{
    class SocketProgramming
    {
        //Socket m_socWorker;
        public AsyncCallback pfnWorkerCallBack;
        public Socket m_socListener;
        public Socket m_socWorker;

        public void sendChat(IPAddress toMessengerIP)
        {
            try
            {
                //create a new client socket ...

                m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                String szIPSelected = toMessengerIP.ToString();
                String szPort = "7777";
                int alPort = System.Convert.ToInt16(szPort, 10);

                System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
                System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
        //        receive();
                m_socWorker.Connect(remoteEndPoint);

                //Send data
                Object objData =(object)"hi dhivi";
                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                m_socWorker.Send(byData);


            }
            catch (System.Net.Sockets.SocketException se)
            {
                //MessageBox.Show(se.Message);
                Console.Out.Write(se.Message);
            }
        }

        public void receive()
        {
            try
            {
                //create the listening socket...
                m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 7777);
                //bind to local IP Address...
                m_socListener.Bind(ipLocal);
                //start listening...
                m_socListener.Listen(4);
                // create the call back for any client connections...
                m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
                //cmdListen.Enabled = false;

            }
            catch (SocketException se)
            {
                Console.Out.Write(se.Message);
            }
        }

        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                m_socWorker = m_socListener.EndAccept(asyn);

                WaitForData(m_socWorker);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                Console.Out.Write(se.Message);
            }

        }

        public class CSocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                //if (pfnWorkerCallBack == null)
                //{
                //    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                //}
                CSocketPacket theSocPkt = new CSocketPacket();
                theSocPkt.thisSocket = soc;
                // now start to listen for any data...
                soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                Console.Out.Write(se.Message);
            }

        }
    }
}

And whenever the users clicks the enter button it should call the sendChat() method.

private void txt_Userinput_KeyDown_1(object sender, KeyEventArgs e) {

    Window parentWindow = Window.GetWindow(this);
    TabItem tb = (TabItem)this.Parent;
    string user = tb.Header.ToString();
    if (e.Key == Key.Return)
    {
        richtxtbox_chatwindow.AppendText(Environment.NewLine + user + " : " + txt_Userinput.Text);
        DBCoding dbObject = new DBCoding();
        SocketProgramming socketObj = new SocketProgramming();                
        socketObj.sendChat(IPAddress.Parse("192.168.15.41"));              
    }
    else { return; }
}

To get ipaddress of the user

public IPAddress getIP()
    {
        String direction = "";
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            direction = stream.ReadToEnd();
        }

        //Search for the ip in the html
        int first = direction.IndexOf("Address: ") + 9;
        int last = direction.LastIndexOf("</body>");
        direction = direction.Substring(first, last - first);
        IPAddress ip = IPAddress.Parse(direction);
        return ip;
    }
13
  • not an answer, a question. what's the exception? ECONNREFUSED ? or something like that? post the error code and the message Commented Oct 15, 2013 at 17:10
  • A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.15.41:7777.This is the error message i got Commented Oct 15, 2013 at 17:12
  • @Marteen can you pls help me Commented Oct 15, 2013 at 17:24
  • Do you get the same result if you try to connect to 127.0.0.1? Commented Oct 15, 2013 at 17:28
  • Also, just to check - I assume you are calling receive at some point? Commented Oct 15, 2013 at 17:33

1 Answer 1

3

You never seem to be calling your receive method. If your application never starts listening, no one will ever be able to connect. If you've tried that, and is getting an exception, post that and we'll go from there.

Sign up to request clarification or add additional context in comments.

11 Comments

wen i call the receive method am getting this exception "An attempt was made to access a socket in a way forbidden by its access permissions"
That could be caused by a number of things - another program listening on the same port, firewall settings, antivirus software.
This is working fine.But why am i not getting for my IPAddress "192.168.15.41" ?
You're saying it's working for 127.0.0.1 but not 192.168.15.41? Firewall or antivirus I'd say. For the other issue, put a breakpoint right at the beginning of OnClientConnect and see if the code ever gets there.
Not really following you there. 127.0.0.1 is the loopback address, it will always loop back to your own computer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.