我在C#中尝试了TCP客户端重用地址
但这不起作用。.所以我有一个问题
我应该在哪里使用重用地址? (客户端|服务器,客户端)
->我只尝试了客户端
使用位置正确吗?
->我在创建客户端后使用了
我试图找到解决方案。但是我做不到。
所以请给我一些帮助。:)
这是我的代码。 (1.服务器,2.客户)
class Program
{
static void Main(string[] args)
{
if(args.Length < 1)
{
Console.WriteLine("Usage : {0} <Bind IP>", Process.GetCurrentProcess().ProcessName);
return;
}
string bindIp = args[0];
const int bindPort = 5425;
TcpListener server = null;
try
{
IPEndPoint localAddress = new IPEndPoint(IPAddress.Parse(bindIp), bindPort);
server = new TcpListener(localAddress);
//server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
server.Start();
Console.WriteLine("Server Start . . .");
while(true)
{
TcpClient client = server.AcceptTcpClient();
//client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
Console.WriteLine("Client Connect : {0} ", ((IPEndPoint)client.Client.RemoteEndPoint).ToString());
NetworkStream stream = client.GetStream();
int length;
string data = null;
byte[] bytes = new byte[256];
while((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.UTF8.GetString(bytes, 0, length);
Console.WriteLine(String.Format("Received : {0}", data));
byte[] msg = Encoding.UTF8.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sended : {0}", data));
}
stream.Close();
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine(e);
}
finally
{
server.Stop();
}
Console.WriteLine("End Server");
}
}
class Program
{
static void Main(string[] args)
{
if(args.Length < 4)
{
Console.WriteLine("Usage : {0} <Bind IP> <Bind Port> <Server IP> <Message>", Process.GetCurrentProcess().ProcessName);
return;
}
string clientIp = args[0];
int clientPort = Convert.ToInt32(args[1]);
string serverIp = args[2];
const int serverPort = 5425;
string message = args[3];
try
{
IPEndPoint clientAddress = new IPEndPoint(IPAddress.Parse(clientIp), clientPort);
IPEndPoint serverAddress = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
Console.WriteLine("Client : {0}, Server : {1}", clientAddress.ToString(), serverAddress.ToString());
TcpClient client = new TcpClient(clientAddress);
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
client.Connect(serverAddress);
byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Console.WriteLine("Sended : {0}", message);
data = new byte[256];
string responseData = "";
int bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.UTF8.GetString(data, 0, bytes);
Console.WriteLine("Received : {0}", responseData);
stream.Close();
client.Close();
}
catch (SocketException e)
{
Console.WriteLine(e);
}
Console.WriteLine("End Client");
}
}