I have a TCP listener that should recieve some messages from a client but when I start this simple server I get an error like this on server.Start():
Only one usage of each socket address (protocol/network address/port) is normally permitted
this is the code that I'm using:
public class ServerThread
{
private readonly int port = 8000;
private readonly IPAddress ip = IPAddress.Parse("xxxx");
/// <summary>
/// constructor, create the server thread
/// </summary>
public ServerThread()
{
Thread serverThread = new Thread(new ThreadStart(serverThreadStart));
serverThread.Start();
Console.WriteLine("Server thread started!");
}
/// <summary>
/// start the server
/// </summary>
private void serverThreadStart()
{
TcpListener server = null;
try
{
server = new TcpListener(ip, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
while (true)
{
Console.WriteLine("Waiting for client connection...");
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
data = data.ToUpper();
Byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Debug.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
}
and the main method simply does this:
static void Main(string[] args)
{
new ServerThread();
}