使用提供的代码here。
在120秒内连续运行时,我的机器上出现SocketException
:
Only one usage of each socket address (protocol/network address/port) is normally permitted 127.0.0.1:24125
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
socket.Close();
之后添加socket.Receive(receiveBuffer);
不会做任何事情。也许很明显,因为Dispose()
无论如何都应该自动调用Close()
。socket
后,等待超过120秒会重置套接字,并且可以再次使用它而不会出错。using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpTestCSharp
{
class Program
{
static void Main(string[] args)
{
string response = "Hello";
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
if (ipAddress != null)
{
IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 24125);
byte[] receiveBuffer = new byte[100];
try
{
using (TcpClient client = new TcpClient(serverEndPoint))
{
using (Socket socket = client.Client)
{
socket.Connect(serverEndPoint);
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Receive(receiveBuffer);
Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));
}
}
}
catch (SocketException socketException)
{
Console.WriteLine("Socket Exception : ", socketException.Message);
throw;
}
Console.ReadLine();
}
}
}
}