Hello!
I need to make a TCP client that will send message to server from certain port (for example 50000). I've tried to call Bind method before Send, and it works, but only for the first time. Message is sent from the port that i've chosen before, but when i'm trying to call it a second or more time, the exception comes: "usually allow to use only one address". When i'm restarting my form it's repeating once again: first - ok, then - exception. I read, that such exception comes, because port from which i sending message has no time for free itself, and it's required more time. Here is the code of my client:
private void button2_Click_1(object sender, EventArgs e)
{
string local_host = System.Net.Dns.GetHostName();
string local_ip_address = Dns.GetHostByName(local_host).AddressList[0].ToString();
IPEndPoint send_point = new IPEndPoint(IPAddress.Parse(local_ip_address), 50000);
Socket send_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint connected_point = new IPEndPoint(IPAddress.Parse(textBoxIPListen.Text),
Convert.ToInt32(textBoxPortListen.Text));
try
{
send_socket.Bind(send_point);
send_socket.Connect(connected_point);
byte[] data = Encoding.Unicode.GetBytes("TestTest");
send_socket.Send(data);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
send_socket.Close();
((IDisposable)send_socket).Dispose();
}
}
What I have tried:
I had recommendation to close socket with
Close() method, use in the end
Dispose(),
Shutdown(),
Disconnect() and
send_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true) but unfortunately nothing works. Is it ever possible to bind client socket everytime before send it ? If so, what should i do, can you please help?