2012-12-03 101 views
0

我對此有點困惑......接收數據前面的垃圾字符...每次都有相同的字符集。我試過這個和其他的例子......一樣的東西。使用msdn.net 4.5中的異步套接字示例的套接字接收緩衝區中的額外字符

正在等待連接... 正在等待連接... 從套接字讀取32個字節。 數據:??▼?? ??^?? ?? ?? ?? ?? ?? asdf :32 發送32個字節到客戶端。

我只是加載和運行這個例子... http://msdn.microsoft.com/en-us/library/fx6588te.aspx

+2

那麼,你發送了什麼數據*?如何? –

+0

在粘貼示例的情況下...我通過telnet連接向服務器發送了「asdf」,服務器在「asdf」之前打印了所有額外的字符。 – user1871750

+0

2秒,當我用telnet檢查... –

回答

0

目前沒有任何垃圾字符;以下是罰款:

static void Client(object state) 
{ 
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); 
    IPAddress ipAddress = ipHostInfo.AddressList[0]; 
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000); 

    using (var client = new TcpClient()) 
    { 
     client.NoDelay = true; 
     client.Connect(localEndPoint); 
     using (var ns = client.GetStream()) 
     { 
      string data = @"this is 
some random data 
with multiple lines 
<EOF>"; // <=== server explicitly expects this as a sentinel value 

      var buffer = Encoding.ASCII.GetBytes(data); 
      ns.Write(buffer, 0, buffer.Length); 

      // note: normally I'd use Socket etc; ReadToEnd is 
      // ... unreliable on a NetworkStream 
      using (var sr = new StreamReader(ns)) 
      { 
       // for this ^^^ to end, it means the server disconnected 
       // the socket, which means it got the <EOF> and shutdown 
       string s = sr.ReadToEnd(); 
       Console.WriteLine("From server:"); 
       Console.WriteLine(s); 
      } 
     } 
    } 
} 
public static int Main(String[] args) { 
    ThreadPool.QueueUserWorkItem(Client); 
    // ^^^ client on a different thread to the server 
    StartListening(); 
    return 0; 
} 

我猜錯誤是在「客戶端」的代碼,你沒有向我們展示。據推測,它不是ASCII編碼的文本,這是服務器期望的。