I’m trying to implement a client server app which a
Server program has a counter which is incremented by one upon request(No counter value provided to a client can be duplicated)
Client program asks the server program to increment the counter and get the incremented value
Server program should be capable of handling multiple clients(at least 5) at a time
The counter value should be shared by all the server threads if any
I have implemented the server and the client apps in seperate projects.When i start running the server and then the client the server programs following line gives a NullReferanceException.
NetworkStream netstream = ((TcpClient)client).GetStream();
I’m new in C#.I want to know how the client can connect to the server and get the incremented value.
I have attached my code here.
Thanks in advance.
MyServer.cs
public abstract class MyServer
{
private static int port = 8080;
private static TcpListener listener;
private static Thread thread;
private static int clientId = 0;
static void Main(string[] args)
{
listener = new TcpListener(new IPAddress(new byte[] {127,0,0,1}),port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
}
private static void Listen()
{
listener.Start();
Console.WriteLine("Listening on: " + port.ToString());
while(true)
{
Console.WriteLine("Waiting for connection....");
Console.WriteLine("Client No: " + clientId);
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start();
}
}
private static void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
Console.WriteLine("Request made");
clientId = clientId + 1;
// String message = "Hello world";
byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Close();
}
}
MyClient.cs
class MyClient
{
static void Main(string[] args)
{
TcpClient tcpClient;
int port = 8080;
NetworkStream stream = null;
tcpClient = new TcpClient("127.0.0.1", port);
Console.WriteLine("Connection was established....");
stream = tcpClient.GetStream();
Byte[] response = new Byte[tcpClient.ReceiveBufferSize];
stream.Read(response,0,(int)tcpClient.ReceiveBufferSize);
String returnData = Encoding.UTF8.GetString(response);
Console.WriteLine("Server Response " + returnData);
tcpClient.Close();
stream.Close();
}
}
You’re starting the thread with no arguments while it expects one (the
TcpStreamof the client). Change this:to this:
By the way, I’d call that thread
clientThreadrather thanlistenThread; the thread isn’t listening, it’s attending to the client.