【问题标题】:Socket Sending and Recieving in C# (while loop)C#中的套接字发送和接收(while循环)
【发布时间】:2017-10-28 19:39:48
【问题描述】:

这是我的代码。我正在编写一个简单的 Socket 测试。

    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);
            }
        }
    }
}

现在的问题是我不能再在我的代码中使用 networkSram,因为它已在使用选项卡的末尾被删除。

谁能帮我解决这个问题,我是 C# 新手,这在 Java 中不存在。

谢谢! 朱利安。

【问题讨论】:

  • 你的代码没有意义——你想达到什么目的?
  • 你应该把你的'while'循环放到'using'块中。您在“使用”块的定义中创建的对象在退出后立即释放。
  • 不,否则发送将不会被执行......这是该问题的以下内容:stackoverflow.com/questions/44226506/…
  • 我想要的很简单,但是 wtf 我不起作用......它是发送一条线,然后在一段时间内收到多条线。

标签: c# sockets line send


【解决方案1】:

您只需将 using 扩展到您正在使用的对象的 所有 用法 - 如果您只看这个词,这是有道理的:花括号内的所有代码都是 使用括号内的对象。所以这至少应该解决这个具体问题:

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);
                }
            }
        }
    }
}

【讨论】:

  • 谢谢!但正如我所说,我尝试过但不起作用该行仅在 while 循环之后发送......
  • using的第二行在while循环结束时执行...
猜你喜欢
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2016-07-28
  • 2013-11-01
  • 2010-11-14
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多