套接字:通常只允许使用每个套接字地址

时间:2015-04-01 16:50:36

标签: c# .net sockets networking network-programming

我想在使用一次后重用一个套接字,但我总是得到subj异常。 我找到了同样问题但没有工作解决方案的多个问题。我尝试了using代码,我尝试了手动关闭 - 但没有成功

一点点样本

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTest
{
    class Program
    {
        static void Main()
        {
            for (int i = 1; i <= 2; i++)
            {
                var encoding = new UTF8Encoding(false);
                var host = Dns.GetHostEntry("localhost");
                var endpoint = new IPEndPoint(host.AddressList[0], 11322);
                Console.WriteLine("Iteration #{0}\tEnpdoint = {1}", i, endpoint);
                try
                {

                    var client = new TcpClient(endpoint);

                    const string message = "Hello world!";
                    byte[] data = encoding.GetBytes(message);
                    client.Connect(endpoint);
                    var stream = client.GetStream();

                    stream.Write(data, 0, data.Length);
                    Console.WriteLine("Sent: {0}", message);


                    byte[] receiveData = new byte[4096];
                    int totalBytes = 0;
                    while (true)
                    {
                        int bytesRead = stream.Read(receiveData, 0, receiveData.Length);
                        totalBytes += bytesRead;
                        if (bytesRead < receiveData.Length)
                            break;
                        Array.Resize(ref receiveData, 2 * receiveData.Length);
                    }

                    var response = encoding.GetString(receiveData, 0, totalBytes);
                    Console.WriteLine("Received: {0}", response);

                    client.Client.Shutdown(SocketShutdown.Both);
                    client.Client.Disconnect(true);
                    stream.Close();
                    client.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                Console.WriteLine();
            }
        }
    }
}

enter image description here

0 个答案:

没有答案