COMP 117 Ping Demonstration Programs & Makefile / C++ Hints

Slides:



Advertisements
Similar presentations
C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
Advertisements

C/c++ 4 Yeting Ge.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation Namespaces Simple Make Files (Ignore all class references.
CSCI 4550/8556 Computer Networks Comer, Chapter 3: Network Programming and Applications.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
Working with Strings Lecture 2 Hartmut Kaiser
Copyright 2012, 2013 & 2015 – Noah Mendelsohn COMP 150-IDS Ping Demonstration Programs & Makefile / C++ Hints Noah Mendelsohn Tufts University
Copyright 2012 & 2015 – Noah Mendelsohn A Brief Intro to the RPC Project Framework Noah Mendelsohn Tufts University
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Big Endian vs. Little Endian Storage of Numeric Data Noah Mendelsohn Tufts University Web:
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
LECTURE LECTURE 14 Exception Handling Textbook p
A Quick Look at C for C++ Programmers Noah Mendelsohn Tufts University Web: COMP.
Lecture 01a: C++ review Topics: Setting up projects, main program Memory Diagrams Variables / Types (some of) the many-types-of-const's Input / Output.
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Eighth Lecture Exception Handling in Java
C++ Lesson 1.
C ++ MULTIPLE CHOICE QUESTION
Java Exceptions a quick review….
Exceptions Error Handling and Recovery
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 6 CS 3370 – C++ Functions.
Eugene Hsu.
C Primer.
A Brief Intro to the RPC Project Framework
Handling Exceptionally Sticky Problems
Compilation and Debugging
Compilation and Debugging
Java Programming Language
Lessons from The File Copy Assignment
Command Line Arguments
CS3340 – OOP and C++ L. Grewe.
Why exception handling in C++?
Working with Strings Lecture 2 Hartmut Kaiser
An Introduction to C Programming
COMP 117 Ping Demonstration Programs & Makefile / C++ Hints
Introduction to Exceptions in Java
EXCEPTION HANDLING.
Object Oriented Programming COP3330 / CGS5409
Tutorial C#.
Lesson 2: Building Blocks of Programming
Exceptions with Functions
Procedural Programming
Brought to you by C++ Tutorial Brought to you by
Working with Strings Lecture 2 Hartmut Kaiser
Data Abstraction: The Walls
Andy Wang Object Oriented Programming in C++ COP 3330
Part B – Structured Exception Handling
When your program crashes
CSC 270 – Survey of Programming Languages
Created by Hwansoo Han Edited by Ikjun Yeom
Exceptions 1 CMSC 202.
Introduction to Programming
Handling Exceptionally Sticky Problems
2009 Test Key.
COMP 150-IDS Ping Demonstration Programs & Makefile / C++ Hints
Today’s Objectives 28-Jun-2006 Announcements
CS31 Discussion 1H Fall18: week 1
CS31 Discussion 1H Winter19: week 1
Exception Handling.
CMSC 202 Lesson 20 Exceptions 1.
CECS 130 Final Exam Review Session
Exceptions and networking
Presentation transcript:

COMP 117 Ping Demonstration Programs & Makefile / C++ Hints COMP 150-IDS: Internet Scale Distributed Systems (Spring 2018) COMP 117 Ping Demonstration Programs & Makefile / C++ Hints Noah Mendelsohn Tufts University Email: noah@cs.tufts.edu Web: http://www.cs.tufts.edu/~noah

What you should get from today’s session A quick look at some details you’ll need to do our programming assignment, including: The framework we’re using C++ Exceptions A tiny bit about inheritance Makefiles C/C++ tips and tricks

Working through the Demo Client

Include Framework and Debug code Preamble Include Framework and Debug code #include "c150dgmsocket.h" #include "c150debug.h" #include <fstream> using namespace std; // for C++ std library using namespace C150NETWORK;

IMPORTANT! Needed for COMP150IDS Framework! Preamble #include "c150dgmsocket.h" #include "c150debug.h" #include <fstream> using namespace std; // for C++ std library using namespace C150NETWORK;

Main pingclient Logic

This is not an ordinary socket…it’s a smart wrapper around a socket Client logic try { C150DgmSocket *sock = new C150DgmSocket(); sock -> setServerName(argv[serverArg]); sock -> write(argv[msgArg], strlen(argv[msgArg])+1); readlen = sock -> read(incomingMessage, sizeof(incomingMessage)); checkAndPrintMessage(readlen, incomingMessage, sizeof(incomingMessage)); } catch (C150NetworkException e) { cerr << argv[0] << ": caught C150NetworkException: " << e.formattedExplanation() << endl; Establishes us as a client…and identifies the server…ports set based on login id

Clients write, then read Client logic try { C150DgmSocket *sock = new C150DgmSocket(); sock -> setServerName(argv[serverArg]); sock -> write(argv[msgArg], strlen(argv[msgArg])+1); readlen = sock -> read(incomingMessage, sizeof(incomingMessage)); checkAndPrintMessage(readlen, incomingMessage, sizeof(incomingMessage)); } catch (C150NetworkException e) { cerr << argv[0] << ": caught C150NetworkException: " << e.formattedExplanation() << endl;

Demo Server

Nasty versions of interfaces introduce errors! Server logic nastiness = atoi(argv[1]); // convert command line string to integer try { C150DgmSocket *sock = new C150NastyDgmSocket(nastiness); c150debug->printf(C150APPLICATION,"Ready to accept messages"); while(1) { readlen = sock -> read(incomingMessage, sizeof(incomingMessage)-1); // … WORK WITH MESSAGE HERE string response = “SOME RESPONSE HERE”; sock -> write(response.c_str(), response.length()+1); } catch (C150NetworkException e) { c150debug->printf(C150ALWAYSLOG,"Caught C150NetworkException: %s\n", e.formattedExplanation().c_str());

Servers read, then write Server logic nastiness = atoi(argv[1]); // convert command line string to integer try { C150DgmSocket *sock = new C150NastyDgmSocket(nastiness); c150debug->printf(C150APPLICATION,"Ready to accept messages"); while(1) { readlen = sock -> read(incomingMessage, sizeof(incomingMessage)-1); // … WORK WITH MESSAGE HERE string response = “SOME RESPONSE HERE”; sock -> write(response.c_str(), response.length()+1); } catch (C150NetworkException e) { c150debug->printf(C150ALWAYSLOG,"Caught C150NetworkException: %s\n", e.formattedExplanation().c_str());

Framework assumes responses go to server/port from which we read Server logic Framework assumes responses go to server/port from which we read nastiness = atoi(argv[1]); // convert command line string to integer try { C150DgmSocket *sock = new C150NastyDgmSocket(nastiness); c150debug->printf(C150APPLICATION,"Ready to accept messages"); while(1) { readlen = sock -> read(incomingMessage, sizeof(incomingMessage)-1); // … WORK WITH MESSAGE HERE string response = “SOME RESPONSE HERE”; sock -> write(response.c_str(), response.length()+1); } catch (C150NetworkException e) { c150debug->printf(C150ALWAYSLOG,"Caught C150NetworkException: %s\n", e.formattedExplanation().c_str());

Inferring who is a server and who is a client NOTE: The socket class imposes a simple notion of client/server on UDP… It decides whether you’re a server or client based on which methods you call first 1) client calls setServer name then writes 2) server starts by doing a read. Not a very robust approach for production code, but handy for these simple programs. nastiness = atoi(argv[1]); // convert command line string to integer try { C150DgmSocket *sock = new C150NastyDgmSocket(nastiness); c150debug->printf(C150APPLICATION,"Ready to accept messages"); while(1) { readlen = sock -> read(incomingMessage, sizeof(incomingMessage)-1); // … WORK WITH MESSAGE HERE string response = “SOME RESPONSE HERE”; sock -> write(response.c_str(), response.length()+1); } catch (C150NetworkException e) { c150debug->printf(C150ALWAYSLOG,"Caught C150NetworkException: %s\n", e.formattedExplanation().c_str());

C++ Inheritance

A super-simple look at C++ Inheritance Base class “Shape” has draw() method with no implementation (=0) class Shape { private: Point position; public: Point getPosition(); virtual void draw() = 0; };

A super-simple look at C++ Inheritance class Shape { private: Point position; public: Point getPosition(); virtual void draw() = 0; }; Each subclass provides its own implementation of draw() Class Circle : public Shape { public: virtual void draw(); }; Class Square : public Shape { public: virtual void draw(); };

A super-simple look at C++ Inheritance Both classes inherit postion() method from parent Class shape { private: Point position; public: Point getPosition(); virtual void draw() = 0; }; Shape *shapeArray[2]; int i; shapeArray[0] = new Circle(); shapeArray[1] = new Square(); for(i=0; i<2; i++) { cout << shapeArray[i] -> position; shapeArray[i] -> draw(); } Class Circle : public Shape { public: virtual void draw(); }; Class Square : public Shape { public: virtual void draw(); };

A super-simple look at C++ Inheritance First time calls Circle::draw, second time calls Square::draw Class shape { private: Point position; public: Point getPosition(); virtual void draw() = 0; }; Shape *shapeArray[2]; int i; shapeArray[0] = new Circle(); shapeArray[1] = new Square(); for(i=0; i<2; i++) { cout << shapeArray[i] -> position; shapeArray[i] -> draw(); } Class Circle : public Shape { public: virtual void draw(); }; Class Square : public Shape { public: virtual void draw(); };

Inheritance and nasty sockets logic The C150NastyDgmSocket class inherits from… Inheritance and nasty sockets logic try { C150DgmSocket *sock = new C150NastyDgmSocket(nastiness); c150debug->printf(C150APPLICATION,"Ready to accept messages"); while(1) { readlen = sock -> read(incomingMessage, sizeof(incomingMessage)-1); // … WORK WITH MESSAGE HERE string response = “SOME RESPONSE HERE”; sock -> write(response.c_str(), response.length()+1); } catch (C150NetworkException e) { c150debug->printf(C150ALWAYSLOG,"Caught C150NetworkException: %s\n", e.formattedExplanation().c_str()); … C150DgmSocket. You can use either type here, unless you want to call methods specific to the “nasty” class.

C++ Exceptions

C++ Exceptions C++ has try/catch/throw for Exceptions try clause runs first try { C150DgmSocket *sock = new C150DgmSocket(); sock -> setServerName(argv[serverArg]); sock -> write(argv[msgArg], strlen(argv[msgArg])+1); readlen = sock -> read(incomingMessage, sizeof(incomingMessage)); checkAndPrintMessage(readlen, incomingMessage, sizeof(incomingMessage)); } catch (C150NetworkException e) { cerr << argv[0] << ": caught C150NetworkException: " << e.formattedExplanation() << endl; Any network exception in try block or methods called by try block takes us here e is of whatever type was “thrown”

C++ Exceptions Exceptions are particularly useful for network code… …no need to “percolate” return codes through layers of method calls Standard COMP 150IDS Exception Class: throw throw C150NetworkException("Client received message that was not null terminated"); When an error occurs, throw an Exception (same as “raise” in other langs): throw C150NetworkException (or other class) Exception classes form a hierarchy…based on class inheritance (no need for you to worry about that if you don’t know C++ inheritance)

Makefiles Dependency – based Command Execution

Variables defined this way… Makefile variables Variables defined this way… # Do all C++ compies with g++ CPP = g++ CPPFLAGS = -g -Wall -Werror -I$(C150LIB) # Where the COMP 150 shared utilities live, including c150ids.a and userports.csv # Note that environment variable COMP150IDS must be set for this to work! C150LIB = $(COMP117)/files/c150Utils/ [… several lines skipped…] pingclient: pingclient.o $(C150AR) $(INCLUDES) $(CPP) -o pingclient pingclient.o …or from environment… (this is one reason you setenv COMP117 /comp/117) …used this way

Targets and dependencies The pingclient target # Do all C++ compies with g++ CPP = g++ CPPFLAGS = -g -Wall -Werror -I$(C150LIB) # Where the COMP 150 shared utilities live, including c150ids.a and userports.csv # Note that environment variable COMP150IDS must be set for this to work! C150LIB = $(COMP117)/files/c150Utils/ [… several lines skipped…] pingclient: pingclient.o $(C150AR) $(INCLUDES) $(CPP) -o pingclient pingclient.o …depends on pingclient.o (and include files, etc.)

When pingclient is older than pingclient.o, etc. … What gets run When pingclient is older than pingclient.o, etc. … # Do all C++ compies with g++ CPP = g++ CPPFLAGS = -g -Wall -Werror -I$(C150LIB) # Where the COMP 150 shared utilities live, including c150ids.a and userports.csv # Note that environment variable COMP150IDS must be set for this to work! C150LIB = $(COMP150IDS)/files/c150Utils/ [… several lines skipped…] pingclient: pingclient.o $(C150AR) $(INCLUDES) $(CPP) -o pingclient pingclient.o ..use g++ to relink it

…and is compiled from that .cpp file Fancier dependencies Each xxx.o file …depends on xxx.cpp %.o:%.cpp $(INCLUDES) $(CPP) -c $(CPPFLAGS) $< …and is compiled from that .cpp file

C cs. C++ Strings

C vs C++ Strings – we use both! C++ provides automatic allocation and useful concatenation operations C char[] arrays needed for formatting message packets File and socket APIs defined in terms of C byte arrays Also…preference For some purposes, printf/scanf are handier than C++ << Etc.

Some hints on strings Won’t try a full tutorial here but, remember that you can convert: char cstring[4] = “abc”; // remember the null! string newstring(cstring); // initialize C++ string // from C string char *fromCPlusPlus = newstring.c_str(); // IMPORTANT: fromCPlusPlus // is stable ONLY until // next change to newstring Our focus is on the distributed system design…performance matters some, but do what’s easy and clean

Stringstreams: useful for formatting and conversions C++ strings do not support <<, but stringstreams do include <sstream> // for stringstream include <iostream> // for cout stringstream ss; // empty stringstream int answer = 25; ss << “The answer is “<< answer << “ pounds” << endl; cout << ss.str(); // get string from stringstream

What I Do (mostly) I mostly use C++ strings: automatic allocation I use or convert to char[] if I’m using APIs that need them I use either printf or stringstreams for formatting or… …concatenate strings with “+” (slower, and edge cases where it doesn’t work) Not all the framework code makes good choices internally…you’ll find some stuff that probably should be cleaned up (e.g. excess conversions)