Hello I am doing a socket program in C# and now I have got a problem. I use this server program code and this client code that I have been finding. I have ben modifying it some. So the problem I haw is that I do want to be able to disconnect from the server, I have been trying and googling it a lot but can't find out how to do it. What is the easy way to do it with this code??
the client code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
namespace soket_client_delen
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
}
private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
// Then Enter key was pressed
if (checkBox1.Checked ==true)
send();
}
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}
private void button1_Click_1(object sender, EventArgs e)
{
send();
}
public void send()
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text +"$");
textBox2.Text = "";
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
and server code:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace soket_serverdelen
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}
Thanks you for all help
Did you try clientSocket.Close()?
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close.aspx
You need to have both sides calling close. Typically, though not a hard and fast rule, the client terminates the connection and the server side responds to that. So, when your client is done transmitting/receiving, the client side calls close. The server side then responds to that and calls close on its side.
For client side:
NetworkStream ns = clientSocket.GetStream();
// send important stuff
// receive important stuff from server
ns.Close();
For the server side:
NetworkStream ns = clientSocket.GetStream();
int bytesRead;
while((bytesRead = ns.Read(buffer, 0, buffer.Length)) >= 0) {
if(bytesRead > 0) {
// do really important stuff
} else if(bytesRead == 0) {
// client has trasmitted FIN packet, close and exit thread
ns.Close();
} else {
// handle error condition
// probably close the connection
}
}
The above code is a model only. I've not tested it. You're using network streams so this example (I think) should be helpful. I usually use select() (from the windows API, .NET exposes it in the Socket class) for doing this. Basically, when either side closes the connection, via Close(), the Windows TCP stacks send a TCP FIN packet. This signals that the originating side wishes to close the connection. Also, someone commented that you should wrap your use of these streams in a using clause. That's imperative if you're not going to call Close() directly.
Typically the client would send a logoff-signal to the server. Upon receiving this message the server closes the connection. The client should run a loop untill serverStream.Socket.Closed = True before exiting.
Related
I am currently learning to program a chat room application that uses a server. So far everything works fine if I run the server and multiple instances of the application on a single machine. When I try to run the server on one machine and the actual chat application from another, I get an exception that reads "a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (Ipaddress)(port)"
Server side code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Text;
using System.Threading;
namespace ChatAppServer
{
class Program
{
public static Hashtable ClientList = new Hashtable();
const int PORT = 321;
string localIp;
static void Main(string[] args)
{
TcpListener sckServer = new TcpListener(PORT);
TcpClient sckClient = default(TcpClient);
int counter = 0;
sckServer.Start();
Console.WriteLine("Chat Server is now Running ....");
counter = 0;
//Parser myParser = new Parser();
while (true)
{
counter = counter + 1;
sckClient = sckServer.AcceptTcpClient();
string clientData = "";
byte[] recieveData = new byte[10025];
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
ClientList.Add(clientData, sckClient);
Broadcast(clientData + " joined the chat", clientData, false);
Console.WriteLine(clientData + " connected to the chat");
handleClient client = new handleClient();
client.ClientStart(sckClient, clientData, ClientList);
}
sckClient.Close();
sckServer.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string userName, bool flag)
{
foreach (DictionaryEntry Item in ClientList)
{
TcpClient sckBroadcast;
sckBroadcast = (TcpClient)Item.Value;
NetworkStream broadcastStream = sckBroadcast.GetStream();
Byte[] broadcastData = null;
if (flag == true)
{
broadcastData = Encoding.ASCII.GetBytes(userName + ": " + msg);
}
else
{
broadcastData = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastData, 0, broadcastData.Length);
broadcastStream.Flush();
}
}
public class handleClient
{
TcpClient sckClient;
string clId;
Hashtable ClientList;
public void ClientStart(TcpClient inSckClient, string clientId, Hashtable clist) {
this.sckClient = inSckClient;
this.clId = clientId;
this.ClientList = clist;
Thread ctThread = new Thread(runChat);
ctThread.Start();
}
private void runChat() {
int requestCount = 0;
byte[] recieveData = new byte[10025];
string clientData = "";
string rCount = null;
while ((true))
{
try
{
requestCount += 1;
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
Console.WriteLine(clId + " : " + clientData);
rCount = Convert.ToString(requestCount);
Program.Broadcast(clientData, clId, true);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
}
Chat room application code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Need for the application
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatApp
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient sckClient = new System.Net.Sockets.TcpClient();
NetworkStream svrStream = default(NetworkStream);
string recieveData = null;
public Form1()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
recieveData = "Connected to Server";
msg();
int serverPort = Convert.ToInt32(txtServerPort.Text);
sckClient.Connect(txtServerIp.Text, serverPort);
svrStream = sckClient.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtUserName.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
Thread ctThread = new Thread(MessageCallBack);
btnSend.Enabled = true;
btnConnect.Enabled = false;
txtUserName.Enabled = false;
txtServerIp.Enabled = false;
txtServerPort.Enabled = false;
ctThread.Start();
}
private void MessageCallBack()
{
while(true)
{
svrStream = sckClient.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = sckClient.ReceiveBufferSize;
svrStream.Read(inStream, 0, buffSize);
string returnData = System.Text.Encoding.ASCII.GetString(inStream);
recieveData = "" + returnData;
msg();
}
}
//function to display data strings
private void msg()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(msg));
}
else
{
lstMessage.Items.Add(recieveData);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
txtMessage.Text = "";
}
I have two troubles with your code :
Do not use .ReceiveBufferSize value because it's a different value of your byte array length. And you can have an index out of range exception.
You have a problem of concurrency in the server side. More than 1 thread try to access to the ClientList and this collection is not thread-safe.
To resolve this, you can use the lock keyword
private static object _lock = new object();
//...
lock (_lock)
{
ClientList.Add(clientData, sckClient);
}
lock (_lock)
{
Broadcast(clientData + " joined the chat", clientData, false);
}
//...
lock (_lock)
{
Program.Broadcast(clientData, clId, true);
}
As you're a beginner, i would give you some tips.
Try to use the asynchronous network functions (better than raw threads), an example there.
There is a lot of tutorials about safety with severals connections in C# (with some thing else, better, than the lock keyword).
This question already has an answer here:
networkStream.Read is blocking
(1 answer)
Closed 8 years ago.
I'm currently doing an application of chat between a server with a client. It works, but then it can only follow the sequence of starting by [client send to server]->[server send to client again]. If server didn't send it back to client, client will remain freeze. I actually want to make my client able to keep on sending to server without those sequence. Is there any suggestion I can use? Like background worker or what? I tried keypress but it doesn't works well. I will try any suggestion, thanks.
The first code is my server code in console application and the second code is my client code in windows forms application.
namespace TcpIpNewServer
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(">> Server started...");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(">> Accepted connection from client...");
while ((true))
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
if (bytesFrom[0].ToString() != "0") //listen from client
{
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$^$~~)(")); //hardcode
Console.WriteLine("<< Client : " + dataFromClient);
}
//var cki = Console.ReadKey(true);
//if (cki.KeyChar == 't')
//{
string serverResponse = Console.ReadLine();
if (serverResponse != null) //write to client
{
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
//}
}
}
}
}
Client code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Msg("Client started...");
try
{
clientSocket.Connect("127.0.0.1", 8888);
NetworkStream serverStream = clientSocket.GetStream();
label1.Text = "Client Socket Program - Server connected...";
}
catch (Exception ex)
{
label1.Text = "Client Socket Program - Server connection failed... Please try again...Make sure server is on...";
}
}
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
if (textBox1.Text != "" && textBox1.Text != null) //write to the server
{
//string trimDataText = Regex.Replace(textBox1.Text, #"s", "");
string cloneTextbox = textBox1.Text + "$^$~~)(";
Msg("Me: " + textBox1.Text);
textBox1.Text = "";
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(cloneTextbox);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
byte[] inStream = new byte[10025]; //read from the server
//if (inStream[0].ToString() != "0")
//{
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
Msg2("Server: " + returndata);
//}
}
private void Msg(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + ">> " + mesg;
}
private void Msg2(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + "<< " + mesg;
}
You'll need to switch to async reading/writing ie. NetworkStream.BeginRead()
http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread%28v=vs.110%29.aspx
I am working on a project where I am going to create a TCP/IP Chat application and I have some problems with passing variables between the classes. The variable data does not get passed on from the handleClient to the main class where data along with clientSocket is saved to a Hashtable. The Hashtable is later going to be used for broadcasting the message to all clients. The error i get is as follows: "Error: The name 'data' does not exist in the current context"
Serverside code:
using System;
using System.IO;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections;
namespace Chat_server
{
public class Program
{
//Creates a list with all clients
public static Hashtable clientList = new Hashtable();
public void Main(string[] args)
{
TcpListener serverSocket = null;
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
serverSocket = new TcpListener(localAddr, port);
// Start listening for client requests.
serverSocket.Start();
int counter = 0;
while (true)
{
counter += 1;
Console.WriteLine("Waiting for a connection... ");
TcpClient clientSocket = serverSocket.AcceptTcpClient();
clientList.Add(data, clientSocket);
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClient hclient = new handleClient();
hclient.startClient(clientSocket);
}
}
}
}
//Class to handle each connection separatly
public class handleClient
{
TcpClient clientSocket;
Hashtable clientList;
public void startClient(TcpClient inClient)
{
this.clientSocket = inClient;
Thread clientThread = new Thread(new ThreadStart(doChat));
clientThread.Start();
}
public void doChat()
{
Byte[] bytes = new Byte[10025];
String data = null;
data = null;
while ((true))
{
try
{
foreach (DictionaryEntry Item in clientList)
{
data = null;
// Get a stream object for reading and writing
NetworkStream stream = clientSocket.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
stream.Flush();
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
clientSocket.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
}
}
}
}
data isn't defined in that function or in the class at:
clientList.Add(data, clientSocket);
how to add in exception showing the input has to be enter, if the user click on connect without entering any input? i would like the have a message box show if the user click on the connect button without entering the name, ip and port. [SOLVED]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace SocketClient
{
public partial class SocketClient : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public SocketClient()
{
InitializeComponent();
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textDisplay.Text = textDisplay.Text + Environment.NewLine + " >> " + readData;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
readData = "Conected to NYP Server ...";
msg();
//clientSocket.Connect("127.0.0.1", 8888);
clientSocket.Connect(textIP.Text, Convert.ToInt32(textPort.Text));
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textName.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private void buttonSend_Click(object sender, EventArgs e)
{
// Show msg box if no server is connected
if (serverStream == null)
{
MessageBox.Show("Please connect to a server first!");
return;
}
// Send text
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
// Clear text
textSend.Text = "";
}
private void textDisplay_TextChanged(object sender, EventArgs e)
{
textDisplay.SelectionStart = textDisplay.Text.Length;
textDisplay.ScrollToCaret();
textDisplay.Refresh();
}
private void textSend_TextChanged(object sender, EventArgs e)
{
buttonSend.Enabled = !string.IsNullOrEmpty(textSend.Text);
}
}
}
if(string.IsNullOrEmpty(textIP.Text) || string.IsNullOrEmpty(textPort.Text) || string.IsNullOrEmpty(textName.Text))
{
MessageBox.Show("Please enter IP address, Port #, and Name");
}
else
{
//they entered stuff...so, try to connect..
}
You can use TcpClient.Connected property to check whether a connection is already established or not.
if(clientSocket.Connected){
.... show error message here
}
else{
... go ahead
}
Your form holds references to both a TcpClient and a NetworkStream instance. Both of these implement IDisposable, so that they must be disposed of explicitly. You must override the Dispose method of the form and dispose of these instances if they are not null.
I am now using the default port number TcpListener serverSocket = new TcpListener(9999);
but because at my client side, i have put a textbox to allow user to manually key in the port number. So how do i make my server side to allow port number from port 1 to 9999 instead
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(9999);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Welcome to NYP Chat Server ");
counter = 0;
while ((true))
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Connected ", dataFromClient, false);
Console.WriteLine(dataFromClient + " has join the chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClinet
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClinet
}//end namespace
Add a setting to your program so that you can change the port...
Project properties -> Settings tab -> create a setting called PortNumber, of type Int32, with a default value of 9999
In your code, retrieve the value with Properties.Settings.Default.PortNumber
EDIT: I misread the question. Do you want to listen to all ports from 1 to 9999 at the same time ?? It doesn't make sense, because
many ports in that range will already be used by other processes
you don't need to listen on so many ports...
If you're worried about having multiple users connected at the same time, that's not an issue : just use a new thread to handle each incoming connection, and call AcceptTcpClient again on the listener on the main thread.
The best option would be to make the port number customizable via the application configuration file.
This would allow the server to change ports without a recompilation.
As far as the code goes, you just need to set the port to use here:
TcpListener serverSocket = new TcpListener(portFromAppConfig);
Also, you shouldn't use ports lower than 1024 - these are reserved ports for system services. You should stick to ports in the higher range of numbers (in general).
You don't normally have a single server listening on multiple ports; it's fairly strange. What you do is accept connections, and then pass them off for processing in another thread, and go back to accepting more connections.