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;
    }
4

1 回答 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.

于 2013-10-15T17:47:36.550 回答