How can I Release TCP/IP adresse and Port win I click on button (close connection)

  • Thread starter Thread starter gaggs1
  • Start date Start date
G

gaggs1

Guest
When I'm tring to use TCP/IP connection for Sending same data to android device, An exception show to me:

System.Net.Sockets.SocketException: Only one of each socket adress(Protocol/network address/ Port) is usually allowed.

It is clear that the last connection still works, and when I want to lunch a new connection the port still buzy.

My Code:

new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;

const int PORT_NO = 7800;
const string SERVER_IP = "192.168.1.118";

while (!m_StopThread)
{

//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(System.Net.IPAddress.Any, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();

//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Connect...");
//---get the incoming data through a network stream---

NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];

//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);



//---write back the text to the client---
//nwStream.Write(buffer, 0, bytesRead);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(m);
Console.WriteLine("Sending back : " + m);
// Send back a response.
nwStream.Write(msg, 0, msg.Length);

}

client.Close();
listener.Stop();
}

}).Start();

And when i try :

listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);


and I want to use an other option by connecting an other device ( new TCP IP connection ) the new device send me nothing, then I want to learn how to release my connection after lunch an other connection.

Continue reading...
 
Back
Top