套接字编程 - 连接尝试失败异常

时间:2013-10-15 17:04:53

标签: c# sockets

我是套接字编程的新手,我正在创建一个聊天应用程序。就像其他应用程序一样,只要我在聊天窗口中输入它就应该将聊天发送给特定用户。为所有用户维护一个数据库以及他们的IP地址。所以每当我选择一个用户发送聊天时,它应该发送到相应的IPAddress。截至目前我正在尝试发送聊天到我自己的机器(所以我硬编码我的机器的IPAddress)。但是当我尝试发送时我得到一个例外我的代码到我的IPAddress.Can任何人请帮助我。

我的套接字编程代码是这个

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

        }
    }
}

每当用户点击enter按钮时,它应该调用sendChat()方法。

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

获取用户的ipaddress

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

1 个答案:

答案 0 :(得分:3)

您似乎永远不会调用receive方法。如果您的应用程序永远不会开始收听,那么任何人都无法连接。如果您已经尝试过,并且正在获得例外,请发布该消息,我们将从那里开始。