2017-05-28 108 views
0

这是我的代码。我正在编写一个简单的Socket测试。在C#中的套接字发送和接收(while循环)

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Runtime.InteropServices; 
using System.IO; 
using System.Text; 
using Microsoft.Win32; 

namespace HelloWorld 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 

      Console.WriteLine("Connexion au serveur 62.210.130.212"); 
      using (client = new TcpClient("62.210.130.212", 35025)) 
      using (NetworkStream networkStream = client.GetStream()) 
      { 
       byte[] usernameBytes = Encoding.ASCII.GetBytes(username); 
       networkStream.Write(usernameBytes, 0, usernameBytes.Length); 
      } 

      while (true) 
      { 
       Byte[] data = new Byte[256]; 
       Int32 bytes = networkStream.Read(data, 0, data.Length); 
       String responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); 
       Console.WriteLine("recieved: " + responseData); 
      } 
     } 
    } 
} 

现在的问题是,我不能在我的代码再使用networkStram,因为它已经在使用标签结束时删除。

有人可以帮我解决这个问题,我是C#的新手,这在Java中不存在。

谢谢! Julien。

+0

你的代码没有意义 - 你想达到什么目的? –

+0

你应该把'while'循环放入'using'区块。您在“使用”块的定义中创建的对象在退出后立即处理。 – Mervin

+0

不,否则发送将不会被执行......这是以下问题:https://stackoverflow.com/questions/44226506/socket-sending-and-recieving-in-c-sharp-while-loop –

回答

0

您只需扩展你使用对象的使用超过所有用途 - 这是有道理的,如果你只是看词:卷曲括号内的所有代码使用对象内部括号。所以这应该至少解决这个具体问题:

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Runtime.InteropServices; 
using System.IO; 
using System.Text; 
using Microsoft.Win32; 

namespace HelloWorld 
{ 
    class Program 
    { 
     public static void Main(string[] args) 
     { 

      Console.WriteLine("Connexion au serveur 62.210.130.212"); 
      using (client = new TcpClient("62.210.130.212", 35025)) 
      using (NetworkStream networkStream = client.GetStream()) 
      { 
       byte[] usernameBytes = Encoding.ASCII.GetBytes(username); 
       networkStream.Write(usernameBytes, 0, usernameBytes.Length); 

       while (true) 
       { 
        Byte[] data = new Byte[256]; 
        Int32 bytes = networkStream.Read(data, 0, data.Length); 
        String responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); 
        Console.WriteLine("recieved: " + responseData); 
       } 
      } 
     } 
    } 
} 
+0

谢谢!但正如我所说,我尝试过,但不工作线路只在while循环后发送... –

+0

使用的第二行在while循环结束时执行... –