这是我的代码。我正在编写一个简单的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。
你的代码没有意义 - 你想达到什么目的? –
你应该把'while'循环放入'using'区块。您在“使用”块的定义中创建的对象在退出后立即处理。 – Mervin
不,否则发送将不会被执行......这是以下问题:https://stackoverflow.com/questions/44226506/socket-sending-and-recieving-in-c-sharp-while-loop –