2009-12-10 79 views
0

我在同一臺機器上同時運行客戶端和服務器。 有沒有人知道上述錯誤?連接到服務器時發生SocketException

服務器

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 
using System.Net.Sockets; 
using System.IO; 
using System.Net; 
namespace Server 
{ 
    public partial class Server : Form 
    { 
     private Socket connection; 
     private Thread readThread; 

     private NetworkStream socketStream; 
     private BinaryWriter writer; 
     private BinaryReader reader; 

     //default constructor 

     public Server() 
     { 
      InitializeComponent(); 

      //create a new thread from server 
      readThread = new Thread(new ThreadStart(RunServer)); 
      readThread.Start(); 
     } 

     protected void Server_Closing(object sender, CancelEventArgs e) 
     { 
      System.Environment.Exit(System.Environment.ExitCode); 
     } 

     //sends the text typed at the server to the client 
     protected void inputText_KeyDown(object sender, KeyEventArgs e) 
     { 
      // send the text to client 
      try 
      { 
       if (e.KeyCode == Keys.Enter && connection != null) 
       { 
        writer.Write("Server>>> " + inputText.Text); 

        displayText.Text += 
         "\r\nSERVER>>> " + inputText.Text; 

        //if user at server enter terminate 
        //disconnect the connection to the client 
        if (inputText.Text == "TERMINATE") 
         connection.Close(); 

        inputText.Clear(); 
       } 
      } 
      catch (SocketException) 
      { 
       displayText.Text += "\nError writing object"; 
      } 
     }//inputTextBox_KeyDown 

     // allow client to connect & display the text it sends 
     public void RunServer() 
     { 
      TcpListener listener; 

      int counter = 1; 

      //wait for a client connection & display the text client sends 
      try 
      { 
       //step 1: create TcpListener 
       IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0]; 
       TcpListener tcplistener = new TcpListener(ipAddress, 9000); 

       //step 2: TcpListener waits for connection request 
       tcplistener.Start(); 

       //step 3: establish connection upon client request 
       while (true) 
       { 
        displayText.Text = "waiting for connection\r\n"; 

        // accept incoming connection 
        connection = tcplistener.AcceptSocket(); 

        //create NetworkStream object associated with socket 
        socketStream = new NetworkStream(connection); 

        //create objects for transferring data across stream 
        writer = new BinaryWriter(socketStream); 
        reader = new BinaryReader(socketStream); 

        displayText.Text += "Connection " + counter + " received.\r\n "; 

        //inform client connection was successful 
        writer.Write("SERVER>>> Connection successful"); 
        inputText.ReadOnly = false; 
        string theReply = ""; 

        // step 4: read string data sent from client 
        do 
        { 
         try 
         { 
          //read the string sent to the server 
          theReply = reader.ReadString(); 

          // display the message 
          displayText.Text += "\r\n" + theReply; 
         } 

        // handle the exception if error reading data 
         catch (Exception) 
         { 
          break; 
         } 

        } while (theReply != "CLIENT>>> TERMINATE" && connection.Connected); 

        displayText.Text += 
         "\r\nUser terminated connection"; 

        // step 5: close connection 
        inputText.ReadOnly = true; 
        writer.Close(); 
        reader.Close(); 
        socketStream.Close(); 
        connection.Close(); 

        ++counter; 
       } 
      } //end try 

      catch (Exception error) 
      { 
       MessageBox.Show(error.ToString()); 
      } 
     } 
    }// end method runserver 
}// end class server 

客戶

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Threading; 
using System.Net.Sockets; 
using System.IO; 
using System.Net; 
namespace Client 
{ 
    public partial class Client : Form 
    { 
     private NetworkStream output; 
     private BinaryWriter writer; 
     private BinaryReader reader; 

     private string message = ""; 
     private Thread readThread; 

     //default constructor 
     public Client() 
     { 
      InitializeComponent(); 

      readThread = new Thread(new ThreadStart(RunClient)); 
      readThread.Start(); 
     } 

     protected void Client_Closing(
      object sender, CancelEventArgs e) 
     { 
      System.Environment.Exit(System.Environment.ExitCode); 
     } 

     //sends the text user typed to server 
     protected void inputText_KeyDown(
      object sender, KeyEventArgs e) 
     { 
      try 
      { 
       if (e.KeyCode == Keys.Enter) 
       { 
        writer.Write("CLIENT>>> " + inputText.Text); 

        displayText.Text += 
         "\r\nCLIENT>>> " + inputText.Text; 

        inputText.Clear(); 
       } 
      } 
      catch (SocketException ioe) 
      { 
       displayText.Text += "\nError writing object"; 
      } 
     }//end method inputText_KeyDown 

     //connect to server & display server-generated text 
     public void RunClient() 
     { 
      TcpClient client; 

      //instantiate TcpClient for sending data to server 
      try 
      { 
       displayText.Text += "Attempting connection\r\n"; 

       //step1: create TcpClient for sending data to server 

       client = new TcpClient(); 
       client.Connect("localhost", 9000); 

       //step2: get NetworkStream associated with TcpClient 
       output = client.GetStream(); 

       //create objects for writing & reading across stream 
       writer = new BinaryWriter(output); 
       reader = new BinaryReader(output); 

       displayText.Text += "\r\nGot I/O streams\r\n"; 

       inputText.ReadOnly = false; 

       //loop until server terminate 
       do 
       { 
        //step3: processing phase 
        try 
        { 
         //read from server 
         message = reader.ReadString(); 
         displayText.Text += "\r\n" + message; 
        } 

        //handle exception if error in reading server data 
        catch (Exception) 
        { 
         System.Environment.Exit(System.Environment.ExitCode); 
        } 
       } while (message != "SERVER>>> TERMINATE"); 

       displayText.Text += "\r\nClosing connection.\r\n"; 

       //step4: close connection 
       writer.Close(); 
       reader.Close(); 
       output.Close(); 
       client.Close(); 
       Application.Exit(); 
      } 
      catch (Exception error) 
      { 
       MessageBox.Show(error.ToString()); 
      } 
     } 
    } 
} 

回答

0

這可能是演戲了你的防火牆。嘗試連接到TCP 80上的www.google.com,以查看您是否可以實際連接。

+0

通常,防火牆會過濾數據包,而不是積極地拒絕他們。 – 2009-12-10 01:52:38

+0

我已關閉防火牆並啓用了端口9000 – 2009-12-10 02:11:14

0

您是否正在使用較新版本的Windows?您可能只在IPv4上進行監聽,但「localhost」正在解析爲IPv6地址,但未找到它。嘗試連接到「127.0.0.1」而不是本地主機,看看結果是否改變。

+0

我使用的是Windows XP。我已更改爲127.0.0.1,但似乎沒有任何更改 – 2009-12-10 02:10:25

+1

您是否看到以下命令的任何結果? netstat -na | findstr 9000 – 2009-12-10 02:28:03

+0

沒有它的相同 – 2009-12-10 09:07:19

0

如果您使用的TCPListener該構造,然後它會讓潛在的服務提供商選擇一個網絡地址,這可能不會被「localhost」的。您可能正在監聽您的LAN/WLAN卡而不是本地主機。

查看TCPListener的MSDN頁面,其中的示例顯示如何使用不同的構造函數,查看其他構造函數以獲取更多示例。

這裏有一種方法:

IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0]; 
TcpListener tcpListener = new TcpListener(ipAddress, 9000);  
+0

對不起,我有點noob在這裏,我在哪裏申報IP地址? 我有錯誤提示在當前上下文中找不到dns – 2009-12-11 03:19:36

+0

Dns位於System.Net命名空間中,因此只需添加「using System.Net」到你的代碼,它應該工作。 – 2009-12-11 06:32:54

+0

好的,當我調試它的錯誤免費,但我仍然有套接字excpetion的問題 – 2009-12-11 09:05:25