I am working on a Master - Slave kind of network relationship between a server and multiple clients.
The server is fine, the problem is that i am new to TCP and do not know how to connect to the server without the client knowing the ip form the start.
If someone could rewrite some of my code so it works, I would be thankful.
The server
namespace Server
{
class Program
{
static void Main(string[] args)
{
TcpListener listen = new TcpListener(IPAddress.Any, 8001);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
listen.Start();
Console.WriteLine(" >> " + "Server Started");
while (true)
{
counter += 1;
clientSocket = listen.AcceptTcpClient();
HandleClinet client = new HandleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
}
}
public class HandleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
clientSocket = inClientSocket;
clNo = clineNo;
Thread ClientThread = new Thread(DoChat);
ClientThread.Start();
}
private void DoChat()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From client-" + clNo + " " + dataFromClient);
serverResponse = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
}
}
The client
namespace Client
{
class Program
{
public static TcpClient tcpclnt = new TcpClient();
static void Main(string[] args)
{
while(true)
{
LoopConnect();
LoopPacket();
tcpclnt.Close();
}
}
private static void LoopPacket()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = tcpclnt.GetStream();
serverResponse = "Give me a command!";
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From server -" + dataFromClient);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
private static void LoopConnect()
{
Console.WriteLine("Connecting.....");
while(true)
{
try
{
tcpclnt.Connect(IPAddress.Any, 8001); // The problem area
break;
}
catch (Exception)
{
Console.Write(".");
}
}
Console.WriteLine("Connected.");
}
}
}
The client should somehow get address of the server. The method is depending on the network type (local or Internet). In case of Internet it's virtually impossible without some known peer. In case of a local network you could use a broadcast UDP request (this method is depending on the local network routing rules).
Related
I am setting up a server to read some network clients using TcpListener. The Client sends some data I verify that data and send a response to that data, the client stays connected and sends a second response and I verify that data and send a response back, its like logging in to the server twice. The first login get sent back to the client just fine but the second time the client responds the server does not show that it received anymore data from the client.
I have tested it by setting up a dummy client (the real client is Cell phone based ODB2). With the dummy client set up I did verify that the first handshake happens but the when the client sends the second set of text it does not show up on the server.
class Program
{
static private TcpListener listener = null;
static private TcpClient client = null;
static private NetworkStream stream = null;
static private int iCount = 0;
static Int32 port = 8090;
static IPAddress localAddr = IPAddress.Parse("192.168.1.17");
static void Main(string[] args)
{
listener = new TcpListener(localAddr, port);
listener.Start();
while (true)
{
try
{
client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
catch (IOException ioex)
{
RestartStream();
}
}
}
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
Byte[] bytes = new Byte[client.ReceiveBufferSize];
stream = client.GetStream();
try
{
int bytesRead = stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
string returndata = Encoding.ASCII.GetString(bytes, 0, bytesRead).Replace("-", "");
byte[] sendBytes;
if (returndata.ToLower().StartsWith("7e") && returndata.ToLower().EndsWith("7e"))
{
//… do stuff with the data and send it back to the client
sendBytes = Encoding.Default.GetBytes(login1);
stream.Write(sendBytes, 0, sendBytes.Length);
stream.Flush();
}
else
{
SaveStream(returndata);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Test Client Code:
//---data to send to the server---
string textToSend = "7E010000360141850000080000000000000000000000000000000000000000000000000000000000000035303030303038003131313131313131313131313131313131F67E";
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
string Text2 = "7E0100003601418535303030303038003131313131313131313131313131313131F67E";
Console.WriteLine("Sending : " + Text2);
byte[] bytesToSend2 = ASCIIEncoding.ASCII.GetBytes(Text2);
nwStream.Write(bytesToSend2, 0, bytesToSend2.Length);
client.Close();
Console.ReadLine();
What I need to happen is my understanding is the client stays connected the whole time and send data over and over, my system seems to accept it once and then stops receiving it, I need it to continue to receive the client data and process it.
Ok so I figured it out, there should be a second while loop in side the thread.
static void Main(string[] args)
{
listener = new TcpListener(localAddr, port);
var clientSocket = default(TcpClient);
listener.Start();
var counter = 0;
while (true)
{
clientSocket = listener.AcceptTcpClient();
var client = new ConnectedDevice();
client.startClient(clientSocket, counter.ToString(), sqlConnString);
}
}
ConnectedDevice class:
class ConnectedDevice
{
private TcpClient _clientSocket;
private string _clientNumber;
private string _sqlConnString;
public void startClient(TcpClient clientSocket, string clientNumber, string sqlConnString)
{
_clientSocket = clientSocket;
_clientNumber = clientNumber;
_sqlConnString = sqlConnString;
var ctThread = new Thread(ProcessClient);
ctThread.Start();
}
private void ProcessClient()
{
while (_clientSocket.Connected)
{
try
{
Byte[] bytes = new Byte[_clientSocket.ReceiveBufferSize];
var networkStream = _clientSocket.GetStream();
networkStream.ReadTimeout = 10000;
int i;
while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Replace("-", "");
byte[] sendBytes;
Console.WriteLine(data);
string sLogin1 = "7E81000013014185000008000000000054523230313731303138303930303137497E";
sendBytes = Encoding.ASCII.GetBytes(sLogin1);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
}
catch (Exception ex)
{
}
}
}
}
I made a chat application (Client + server) with following model:
http://csharp.net-informations.com/communications/csharp-chat-server-programming.htm
The difference is, that i made the client in a console application too. Here's the code of my Client Class:
class Program
{
static TcpClient clientSocket = new TcpClient();
static NetworkStream serverStream = default(NetworkStream);
static string readData = null;
static void Main(string[] args)
{
connect();
while (true)
{
string send = Console.ReadLine();
byte[] outStream = Encoding.ASCII.GetBytes(send + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
}
private static void connect()
{
readData = "Connected to Chat Server...";
msg();
clientSocket.Connect("localhost", 8888);
serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes("somerandomusername" + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private static 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 = Encoding.ASCII.GetString(inStream);
if (returndata != null)
{
readData = "" + returndata;
msg();
}
}
}
private static void msg()
{
Console.WriteLine(">> " + readData);
}
}
and here's the code from my Server class:
class Program
{
public static Hashtable clientsList = new Hashtable();
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();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room");
handleClient client = new handleClient();
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 client in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)client.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + ": " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
}
}
public class handleClient
{
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)
{
clientsList.Remove(clNo);
Console.WriteLine(clNo + " hat den Chat verlassen");
break;
}
}
}
}
Somehow the client displays a lot of empty lines when receiving messages. Here's a screenshot: http://i.stack.imgur.com/CoF5B.png.
above the first red marker there are empty lines. it marks the area where i typed in my message, pressed enter and the server response was written. to see it i would have to scroll down to the red marker. then there are the empty lines. the second red marker marks the area where the next message would appear.
I would be really thankful if you could help me removing this problem.
I see what your problem is here is the fixed code (in the client):
private static void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
buffSize = clientSocket.Available;
byte[] inStream = new byte[buffSize];
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
if (returndata != null)
{
readData = "" + returndata;
msg();
}
}
}
You where reading the buffer size into an array you want the available bytes.
David
You are sure you are receiving any text? Are you sending text correctly? Are you getting any errors? Set breakpoints before the broadcast of data and also a breakpoint at the receiving end and check if your variables do contain what you expect they contain.
Is it not that you are trying to read from the Stream which does not have any data and gives you dummydata what results in the application printing new lines with no text because it just has no text to send?
Are the amount of lines of empty text the same as the length of the string you send?
Your problem is the misuse of Encoding.ASCII.GetString:
A byte value of 0 will get converted into space, not into '\0' as you might suspect. And since you initialize it with 10025 zeros you have a bunch of spaces filling up your lines.
Trimming your returndata before appending it to readData will solve this problem but will have side effects like not allowing leading and trailing spaces in your message.
You can try this to understand the problem:
static void Main(string[] args)
{
byte[] lolempty = new byte[1024];
string encoded = Encoding.ASCII.GetString(lolempty);
Console.WriteLine(encoded.Length.ToString());
Console.WriteLine("[{0}]", encoded);
}
I'm having communication problems with my Program.cs class and my handleClinet.cs class.. Program handles accepting connection from every new client that attempts connecting, and handleClinet is responsible for handling every client's individual interaction.
I have a while loop in each class which is, i assume, where the problem lies.. but I'm not sure how else to do this. The server responses are not corresponding to what they're supposed to be responding. (i.e. not going into my broadcast function and executing the statements in the Program while loop) does anyone have a solution to this? Thanks in advance
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
UdpClient server = new UdpClient(8888);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
string data = "";
Console.WriteLine("Auction Server Started ....");
while (true)
{
try
{
//Reads data
byte[] inStream = server.Receive(ref remoteEndPoint);
data = Encoding.ASCII.GetString(inStream);
Console.WriteLine("REGISTER Client at " + remoteEndPoint);
byte[] sendBytes = Encoding.ASCII.GetBytes("REGISTERED " + remoteEndPoint.ToString());
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);
handleClinet client = new handleClinet();
clientsList.Add(data, server);
client.startClient(server, data, clientsList, remoteEndPoint);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
//break;
}
}
}
//Broadcast method is used to send message to ALL clients
public static void broadcast(UdpClient dest, string msg, string uName, bool flag, IPEndPoint sendEP)
{
foreach (DictionaryEntry Item in clientsList)
{
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
dest.Send(broadcastBytes, broadcastBytes.Length, sendEP);
}
}
}//end Main class
}
public class handleClinet
{
UdpClient clientSocket;
string clNo;
Hashtable clientsList;
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
public void startClient(UdpClient inClientSocket, string clineNo, Hashtable cList, IPEndPoint tempEP)
{
this.myEP = tempEP;
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;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
byte[] received = clientSocket.Receive(ref remoteIPEndPoint);
dataFromClient = Encoding.ASCII.GetString(received);
Console.WriteLine(dataFromClient);
rCount = Convert.ToString(requestCount);
if (dataFromClient.Contains("DEREGISTER"))
Program.broadcast(clientSocket, "DREG-CONF", clNo, true, myEP);
else
Program.broadcast(clientSocket, dataFromClient, clNo, true, myEP);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
break;
}
}//end while
}//end doChat
} //end class handleClinet
}
I am trying to get a multi-threaded UDP client/server going, but i'm running into problems on the server side. When a client attempts to register, a thread is created and all the interactions for that client are handled in that thread, but for some reason it only enters the thread once then exits right away.. can anyone help figure out why this happens? -Thanks in advance..
namespace AuctionServer
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
//IPAddress ipAd = IPAddress.Parse("255.255.255.255");
UdpClient server = new UdpClient(8888);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
string data = "";
int listSize = 0;
Console.WriteLine("Auction Server Started ....");
listSize = clientsList.Count;
while (true)
{
//Reads data
byte[] inStream = server.Receive(ref remoteEndPoint);
data = Encoding.ASCII.GetString(inStream);
//Console.WriteLine("REGISTER " + remoteEndPoint);
if (!data.Contains("DEREGISTER "))
{
byte[] sendBytes = Encoding.ASCII.GetBytes(data + remoteEndPoint.ToString());
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);
handleClinet client = new handleClinet();
Console.WriteLine(data);
clientsList.Add(data, server);
client.startClient(server, data, clientsList, remoteEndPoint);
data = "";
}
}
}
//Broadcast method is used to send message to ALL clients
public static void broadcast(UdpClient dest, string msg, string uName, bool flag, IPEndPoint sendEP, Hashtable clientsList)
{
foreach (DictionaryEntry Item in clientsList)
{
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
dest.Send(broadcastBytes, broadcastBytes.Length, sendEP);
}
}
}//end Main class
}
namespace AuctionServer
{
public class handleClinet
{
UdpClient clientSocket;
string clNo;
Hashtable clientsList;
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
public void startClient(UdpClient inClientSocket, string clineNo, Hashtable cList, IPEndPoint tempEP)
{
this.myEP = tempEP;
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;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
//Thread.Sleep(1000);
if (requestCount == 0)
{
Console.WriteLine("Thread Created");
requestCount++;
}
byte[] received = clientSocket.Receive(ref remoteIPEndPoint);
dataFromClient = Encoding.ASCII.GetString(received);
Console.WriteLine(dataFromClient);
if (dataFromClient.Contains("DEREGISTER"))
clientSocket.Send(received, received.Length, remoteIPEndPoint);
//Program.broadcast(clientSocket, "DREG-CONF", clNo, true, myEP, clientsList);
//else
// Program.broadcast(clientSocket, dataFromClient, clNo, true, myEP, clientsList);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
break;
}
}//end while
}//end doChat
}
The two loops run on different threads. So the loop in Main() is executing concurrently with the loop in your handleClinet class.
If you want to switch to the handleClinet class's loop and debug it, then use the Threads window in the debugger (Debug menu, Windows menu item, then Threads...or press Ctrl-D, T) to switch to that thread. Then you can see the call stack and state of that thread.
Note that this may not work on the Express version of Visual Studio. I haven't tried the most recent version, but past versions did not support the Threads window. (You can still debug a specific thread by setting a breakpoint there…it's just that you can't switch to the thread manually).
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.