2013-10-15 98 views
2

我是新的套接字編程,並且正在創建一個聊天應用程序。與其他應用程序一樣,每當我按下聊天窗口中的輸入時,它都應該將聊天發送給特定用戶。所有用戶以及他們的IPAddresses.So每當我選擇一個用戶發送聊天,它應該發送到相應的IPAddress.As現在我試圖發送聊天到我自己的機器(所以我硬編碼我的機器IPAddress)。但是當我嘗試將我的代碼發送給我的IP地址時出現異常,可以請任何人幫助我。套接字編程 - 連接嘗試失敗異常

我對套接字編程代碼是這樣

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

     } 
    } 
} 

每當用戶點擊確認按鈕,應該調用sendChat()方法。

私人無效txt_Userinput_KeyDown_1(對象發件人,發送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; } 
} 

得到用戶的ip地址

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

不是一個答案,一個問題。 有什麼例外? ECONNREFUSED?或類似的東西?發佈錯誤代碼和消息 – Marteen

+0

連接嘗試失敗,因爲連接方在一段時間後沒有正確響應,或者由於連接的主機未能響應192.168.15.41:7777而導致建立的連接失敗。這是我得到的錯誤消息 –

+0

@Marteen你能幫我嗎 –

回答

3

你似乎從來沒有被調用你receive方法。如果您的應用程序從未開始收聽,則無人能夠連接。如果您已經嘗試過,並且發生異常,請發佈該信息,然後我們將從此處開始。

+0

文我打電話receive方法得到這個異常「試圖訪問一個套接字一種被其訪問權限禁止的方式「 –

+0

這可能是由許多事情引起的 - 另一個程序在同一端口上偵聽,防火牆設置,防病毒軟件。 – Chris

+0

這工作正常。但爲什麼我沒有得到我的IP地址「192.168.15.41」? –