连接到服务器时发生SocketException

连接到服务器时发生SocketException

问题描述:

我在同一台机器上同时运行客户端和服务器。 有没有人知道上述错误?连接到服务器时发生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()); 
      } 
     } 
    } 
} 

这可能是演戏了你的防火墙。尝试连接到TCP 80上的www.google.com,以查看您是否可以实际连接。

+0

通常,防火墙会过滤数据包,而不是积极地拒绝他们。 – 2009-12-10 01:52:38

+0

我已关闭防火墙并启用了端口9000 – 2009-12-10 02:11:14

您是否正在使用较新版本的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

mk, 我想tcplistener/tcpclient简单的应用程序。 。 。 TheEruditeTroglodyte

+0

我需要使用我的GUI作为必须 – 2009-12-10 05:22:17

如果您使用的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