2017-04-20 189 views
0

我正在使用套接字进行TCP-IP连接,并且想从客户端建立简单的系统发送接收。C#客户端套接字多次发送和接收

Socket sck; 
     sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
     IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345); 
     try 
     { 
      sck.Connect(localEndpt); 
     } 
     catch 
     { 
      Console.Write("Unable to Connect"); 
     } 
     while (true) 
     { 
      Console.WriteLine("Enter Text"); 
      string sendtext = Console.ReadLine(); 
      byte[] Data = Encoding.ASCII.GetBytes(sendtext); 
      sck.Send(Data); 
      Console.WriteLine("Data Sent!"); 

      byte[] bytesReceived = new byte[sck.ReceiveBufferSize]; 
      int bytes = 0; 
      String strReceived = ""; 

      int dataAvailable = 0; 
      while (dataAvailable == 0 || dataAvailable != sck.Available) 
      { 
       dataAvailable = sck.Available; 
       Thread.Sleep(100); // if no new data after 100ms assume transmission finished 
      } 

      if (sck.Available > 0) 
      { 
       bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0); 
       strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes); 
      } 

      Console.WriteLine("Received from server: " + strReceived); 
     } 
     Console.Read(); 

的问题是,首先要求去throught但第二次却不会,因为插座已不存在(插座“速效”的属性值是0)。我究竟做错了什么? (按顺序)建立多个发送请求请求的最简单方法是什么?

回答

0

Socket. Available确实表明插座是否可用,但传入的数据可用于阅读:
https://msdn.microsoft.com/en-us/library/ee425135.aspx

你的程序了发送消息后立即退出,因为它会检查答复(输入数据) 。在检查数据之前使用Thread.Sleep

也许该消息还没有被发送,因为Socket.Send只是将它放在网络接口卡的输出缓冲区中。当套接字最终发送消息时,它会调整连接状态。如果它没有回复(在TCP连接上),它会告诉你,当你查询状态时,它被断开。在UDP上,它会告诉你什么,因为UDP是无连接的。

0

此代码工作正常,我

private List<Socket> _clients = new List<Socket>(); 
    private Thread _dataReceiveThread; 
    private bool _isConnected; 

    private void DataReceive() 
    { 
     while (_isConnected) 
     { 
      List<Socket> clients = new List<Socket>(_clients); 
      foreach (Socket client in clients) 
      { 
       try 
       { 
        if (!client.Connected) continue; 
        string txt = ""; 
        while (client.Available > 0) 
        { 
         byte[] bytes = new byte[client.ReceiveBufferSize]; 
         int byteRec = client.Receive(bytes); 
         if (byteRec > 0) 
          txt += Encoding.UTF8.GetString(bytes, 0, byteRec); 
        } 
        if (!string.IsNullOrEmpty(txt)) 
         /* Here you can access the text received in the "txt" */ 
       } 
       catch (Exception e) 
       { 
        Exception_Handler(e); 
       } 
      } 
     } 
    } 

只需运行该代码上手

_isConnected = true; 
_dataReceiveThread = new Thread(DataReceive); 
_dataReceiveThread.Start(); 
相关问题