/* Server.cs * Version: Dec. 5, 2014 * * Changelog: * Dec. 5, 2014: ServerConnection updated; * Dec. 4, 2014: More new exercises * Dec. 3, 2014: New exercises, clarifications on some old ones * Dec. 2, 2014: Initial version, multithreading exercises */ using System; using System.Text; using System.Threading; using System.Net.Sockets; using System.Collections; using System.Drawing; namespace RIPS { class Server { Socket s; int port; static public void Main (string [] args) { Run (args); } static public void Run (string [] args) { Server s; s = new Server (); s.InitRegistry (); s.Listen (); s.Register (); s.Work (); } public Server () { /* Exercise 21: just the constructor * ================================= * * This is the constructor of the Server class. As we did for the * client, we need to initialize the socket "s" to a TCP over IPv4 * socket. * * You can remove all lines of code below, within this function * (they are there to avoid a compilation warning). */ s = null; port = 0; // these two lines are here just to avoid a compiler warning // remove them !! Console.WriteLine (s); Console.WriteLine (port); } void InitRegistry () { /* Exercise 22: writing on the Windows registry * ============================================ * * Our server will store some configuration on the Windows * registry. This will just be the port number were the server * listens. * * This method will look up the registry for the specific key * storing the port number. If the key is not found, it will * create one with a default value. If the key is there, it will * just return. * * All configuration of the server will be stored at the key * * HKEY_CURRENT_USER\RIPS\Server * * The port number will be stored under the name "DefaultPort". * * Your task now is to check whether the name "DefaultPort" is * present the key mentionned above. If yes, just return. If not, * create it and give it some value of your choice in the range * 3030 to 3039. */ } void Listen () { /* Exercise 23: bind and listen * ============================ * * When this method is called, the socket "s" will have already * been created. Your task here is to bind it so that it will be * able to receive connections from ALL network interfaces. You * will retrieve the port number from the Windows registry, it is * stored in the name "DefaultPort", hanging from the key * * HKEY_CURRENT_USER\RIPS\Server * * Then put the socket in listening mode, with a queue of 5 * connections. */ } void Register () { /* Exercise 24: making public the IP and port of your server * ========================================================= * * Once you have started your server, since you know the IP * address and port where it listens, you could perfectly connect * to it from your client. * * But that would be too easy, we are going to make it more * interesting. * * Once the server is listening, i.e., you already executed the * Listen() method, it will make public the IP and port where it * listens, so any client can find this information and connect to * it. For that, you will make an HTTP request to a web service * that will store this information online, and accessible to * anyone visiting the following URL: * * http://lipn.univ-paris13.fr/~rodriguez/teach/dotnet/2014-15/rips/servers.php * * Assume your name is "Rodriguez", your IP is "10.11.12.13", and * the port is "3035". To submit it for publication all you need * to do is an HTTP GET of the following URL (try it with your * browser) * * http://lipn.univ-paris13.fr/~rodriguez/teach/dotnet/2014-15/rips/servers.php?name=Rodriguez&ip=10.11.12.13&port=3035 * * Your task now is to submit your name, ip address and port where * this server is listening, using the schema above. */ } void Work () { /* Exercise 25: the service loop * ============================= * * Write an infinite loop, where you * * - Accept a new client from the socket "s" * - Create an object of type ServerConnection, passing the new * socket * - Invoke the method Start from the new ServerConnection object, * it will start a thread dealing with this new client (see next * exercise) * */ } static void Test1 () { /* Exercise 01: first steps with threads * ===================================== * * Write a function that takes as argument a reference of type * "object", and which prints the thread identifier, the object * and the current time (minutes, seconds, and miliseconds). * * From Test1, create 10 threads executing this function, each one * will receive the string "my data %d", where %d will be replaced * by a number from 0 to 9. Once created, wait for them and return * from Test1 once all of them have terminated (do not use * the method Thread.Sleep). * * To execute this method, call it from the Main method (which * right now calls the Run() method) * * Reference: classes System.Thread, System.DateTime */ } static void Test2 () { /* Exercise 02: using the thread pool * ================================== * * Copy the function we wrote for Exercise 01 and modify the copy * adding a sleep of 5 seconds after the WriteLine statement. * Print again something to the console just before exiting the * thread. * * From Test2, create 10 threads executing this function using the * thread pool. Just before and just after creating the threads, * print the current time (with millisecond accuracy). To wait for * the threads to finish, wait for 8 seconds and then return. * * What do you observe? Can you see all threads terminating? Why? * * How long does Test2 take to call 10 times to the thread pool? * Compare with Exercise 01. Also, are threads being created * "immediately"? Are they starting to run "immediately" after * they are created? What is the * * Substitute the 5 seconds sleep in the thread body for a 50 * millisecond sleep. What do you observe? Observe the times taken * to start executing your function and the thread ids on which * the function is being executed across the 10 calls. * * Reference: * classes System.Thread, System.ThreadPool, System.DateTime */ /* Exercise 03: synchronization counters * ===================================== * * After having finished the previous exercise, make Test2 to wait * for the termination of the last and to exit immediately after * (instead of sleeping 8 seconds). Use an CountdownEvent object. * * What happens with Test2 if one of the threads die (for * instance, due to an unhandled exception that only kills the * thread and not the process)? */ } static void Test3 () { /* Exercise 04: passing data * ========================= * * Create a thread an pass three integer variables to it. You are * not allowed to use the argument of the Thread.Start () method. * * Hint: use the same idea as with the InstanceMethod of the first * example at * http://msdn.microsoft.com/en-us/library/ts553s52(v=vs.110).aspx */ } static void Test4 () { /* Exercise 05: mutual exclusion (locking) * ======================================= * * Define a class that stores two public integer variables, "a", * and "b". Create an instance and launch 15 threads, passing * them a reference that instance. * * The method Test5 will monitor every 50 ms (milliseconds) * whether the two integers are the same, and will print a message * if they are not. * * Each thread will execute the same function, it will iterate 10 * times the following actions * - pick a random number from -5 to +5 * - increment "a" with that number * - sleep 100 ms * - increment "b" with the same number * * Observe that you are writing "a" and "b" on the threads, and * reading them from Test5. Use the appropriate synchronization * primitives to avoid having data corruption on the variables. * * Can Test5 detect the two integer variables having different * values? * * Now use a synchronization primitive to protect the accesses to * the integer variables so that the update is atomic. That is, * Test5 will never be able to see the two variables having * different values. * * Use the lock statement in first place. * Then modify the code to use System.Threading.Monitor. * Then modify it again to use an EventWaitHandle (!!) * * Reference: * class System.Random, method Next(int, int) * class System.Interlocked */ } static void Test5 () { /* Exercise 06: signaling, one to all * ================================== * * Start 5 threads in a loop, and use the appropriate * synchronization primitives so that, right after each one of * them starts executing, they block. The user will type a key, * Test3 will read it, and will tell *all threads* to continue * using one single operation. * * You can use at most one synchronization object / primitive. * */ } static void Test6 () { /* Exercise 07: signaling, all to one * ================================== * * Fill the body of Test6, and create additional methods as * needed, to achieve the following: * * - Print the time (with millisecond accuracy) * - Create two EventWaitHandles * - Launch 10 threads, each one does the following: * - Choose a random number between 600 and 1000 * - Print the thread id, the time, and the number * - Sleep that number of milliseconds * - Signal on the first EventWaitHandle * - Sleep for 2 seconds * - Signal the second EventWaitHandle * * In Test6, just after creating the threads, use the first * EventWaitHandle to wait for *the first* thread waking up from * the first sleep. Print the current time. Then wait *for all* * threads to signal on the second EventWaitHandle. * */ } static void Test7 () { /* Exercise 10: simple TCP server (accepting only 1 connection) * ============================================================ * * Open a TCP listening socket accepting connections from any * network card of your computer (see parameters of the Bind * method), accept a single client and send it whatever he/she * sends to you. Exit the server whenever the client closes the * connection. * */ } static void Test8 () { /* Exercise 11: multithreaded TCP server * ===================================== * * As before, open a TCP listening socket accepting connections * from any network card of your computer. In an infinite loop, do * the following: * - accept new client connection * - launch a thread and pass client socket to it * - the thread will, as before, echo to the connection whatever * it reads from it * - terminate the thread whenever the client closes the * connection */ } } class ServerConnection { // the connection socket and the Bencode codec Socket s; Bencode codec; // 2-dimension array containing the image data internal Color [,] image; internal int width; internal int height; // a copy of the request message, to make parameters available SortedList request; // a WaitHandle to signal the ConnectionThread the end of the work by // the WorkerThreads CountdownEvent end; public ServerConnection (Socket conn) { /* Exercise 26: creating a new thread * ================================== * * Add a new field to store a Thread object, and initialize it so * it will execute the method ConnectionThread (using the same * principle as in Exercise 04). * * And remove the Console.WriteLine calls at the bottom, they are * there just to avoid a compilation warning. */ s = conn; codec = new Bencode (RecvByte, SendByte); image = null; width = height = 0; request = null; end = null; // these two lines are here just to avoid a compiler warning // remove them !! Console.WriteLine (s); Console.WriteLine (codec); Console.WriteLine (image); Console.WriteLine (width); Console.WriteLine (height); Console.WriteLine (request); Console.WriteLine (end); } public void Start () { /* Exercise 27: starting the thread * ================================ * * Just invoke the method Start of the thread you created on the * constructor of this class. */ } void ConnectionThread () { /* Exercise 29: the thread handling the client connection * ====================================================== * * This method is the main body of the thread handling the * connection with the client. The goal here is to communicate * with the client, to split the image in pieces, to distribute * them to different threads, and to reply the client with the * final result. The server will only accept one request from the * client, closing the connection after replying to the client. * * You will need to * * - parse the request from the client, detecting possible * inconsistencies or missing data (for instance, headers) and * possibly replying the client with an error * - allocate into the field "image" a 2D array with the received * image data, correctly setting the "width" and "height" fields * - initialize the appropriate synchronization objects so as to * correcly communicate to and from the worker clients * (method WorkerParams.WorkerThread, see below) * - partition the image into equal fragments and to construct, * for each fragment, an object of type WorkerParams associated * to it (see comments in the constructor of WorkerParams for * details) * - launch, using the ThreadPool, the WorkerThread method of * each WorkerParams object you just created * - wait for all threads to finish, using the "end" * CountdownEvent event (as you did in Exercise 03). * - if necessary, to aggregate the results of the computation * made by the threads * - reply the client with the resulting image, or with an error * if something went wrong * - close the socket * * To store the result image, you will need to define in this * class a new 2-dimensional array where the worker threads will * write. They will be able to access it through the reference to * this class that we pass via the constructor of WorkerParams * (which in turn stores it in a local field). For the histogram * you will need another field to store the table. * * Since your worker threads will concurrently write to these * fields, you will need to adecuately synchronize the access to * them. Think well before you write. * * The requests received from the client and the replies that the * server is expected to send back are defined in Client.cs. * * Be tidy. If you feel it is necessary, define new methods for * dealing with each different request that the client may send. * And remember to appropriately handle exceptions here as * necessary, as they could otherwise kill the server. */ } private byte RecvByte () { /* Exercise 28: you already know what * ================================== * * Implement the RecvByte and the SendByte (below) methods as you * did for the client. They will, respectively, read and write * data from the socket into the Bencoding coder/decoder of this * class (field "codec"). Remember, throw an exception if, when * you try to read, you find the connection already closed. */ return 0; } private void SendByte (byte b) { } } class WorkerParams { ServerConnection conn; int minx, miny; int maxx, maxy; public WorkerParams (ServerConnection c, int _minx, int _miny, int _maxx, int _maxy) { /* * The parameter c is a reference to the object whose thread * created this object, it contains the image (c.image) and the * request (c.request) received from the client. * * _minx, _miny, _maxx, _maxy are the coordinates defining the * fragment of the image this object is responsible of processing */ conn = c; minx = _minx; miny = _miny; maxx = _maxx; maxy = _maxy; // these two lines are here just to avoid a compiler warning // remove them !! Console.WriteLine (conn); Console.WriteLine ("", minx, miny, maxx, maxy); } public void WorkerThread () { /* Exercise 30: do the job! * ======================== * * This method will be the main body of the thread processing a * fragment of the image. The image is accessible through * "conn.image", the fragment you need to process is defined by * the fields of this object. * * The algorithm you have to apply to the image it is whatever * conn.request['request'] is asking you to do. * */ } } } // vim: set efm=%f(%l\\,%c)\:\ %m: