2016-08-15 120 views
2

我試圖通過套接字連接將數據從客戶端發送到服務器。我成功發送第一個數據,但當我嘗試發送第二個它永遠不會發送,當我嘗試發送第三個它給我Sockets.SocketException我該如何解決?服務器/客戶端套接字連接

服務器

byte[] buffer = new byte[1000]; 


     IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName()); 
     IPAddress ipAddress = iphostInfo.AddressList[0]; 
     IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080); 

     Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 


     sock.Bind(localEndpoint); 
     sock.Listen(5); 



     while (true) { 
      Socket confd = sock.Accept(); 

      string data = null; 

      int b = confd.Receive(buffer); 

      data += Encoding.ASCII.GetString(buffer, 0, b); 

      Console.WriteLine("" + data); 

      confd.Close(); 
     } 

客戶

byte[] data = new byte[10]; 

     IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName()); 
     IPAddress ipAdress = iphostInfo.AddressList[0]; 
     IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080); 

     Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 


     try { 

      client.Connect(ipEndpoint); 
      Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString()); 


      while (true) { 

       string message = Console.ReadLine(); 
       byte [] sendmsg = Encoding.ASCII.GetBytes(message); 
       int n = client.Send(sendmsg); 
      } 


     } 
     catch (Exception e) { 
      Console.WriteLine(e.ToString()); 
     } 

     Console.WriteLine("Transmission end."); 
     Console.ReadKey(); 
+1

因爲在您的服務器上連接後,您會收到1個字符串,並關閉連接。 – BugFinder

+0

但是我們不是再次打開嗎? – Pareidolia

+0

你的客戶不顯示任何形式的關閉...所以跟蹤你的代碼,它會告訴你什麼是錯的 – BugFinder

回答

2

好吧,有什麼愚蠢的錯誤。這裏是解決方案,我們應該接受一次套接字。

while (true) { 
    Socket confd = sock.Accept(); 
    string data = null; 
    int b = confd.Receive(buffer); 
    data += Encoding.ASCII.GetString(buffer, 0, b); 
    Console.WriteLine("" + data); 
    confd.Close(); 
} 

改爲

Socket confd = sock.Accept(); 
while (true) { 
    //Socket confd = sock.Accept(); 
    string data = null; 
    int b = confd.Receive(buffer); 
    data += Encoding.ASCII.GetString(buffer, 0, b); 
    Console.WriteLine("" + data); 
    //confd.Close(); 
} 

如果有關於插座的任何文檔,評論它,請。我想閱讀。

+0

http://blog.stephencleary.com/2009/04/tcpip-net-sockets-faq.html – ntohl