2016-08-15 118 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