33 Pages

9_Lab2Primer

Course: SENG 130, Fall 2009
School: Virgin Islands
Rating:
 
 
 
 
 

Word Count: 1561

Document Preview

2C Lab Primer I/O in Java Sockets Threads More Java Stuffs Server Flow Start the server with a port if specified (if not, start the server with a default port of 7000) 2. Create a Polling Socket 3. Start the server running "forever" and wait for a client to connect 4. Open I/O to client 5. When connected, send a message to allow client to know they are connected 6. Accept a request from the...

Register Now

Unformatted Document Excerpt

Coursehero >> Other International >> Virgin Islands >> SENG 130

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
2C Lab Primer I/O in Java Sockets Threads More Java Stuffs Server Flow Start the server with a port if specified (if not, start the server with a default port of 7000) 2. Create a Polling Socket 3. Start the server running "forever" and wait for a client to connect 4. Open I/O to client 5. When connected, send a message to allow client to know they are connected 6. Accept a request from the client 7. Respond to the client's request 8. Client port and I/O are closed * Servers run forever 1. Input/Output in Java In Java, there are 2 types of major I/O streams classes we are looking at Reader/Writer: ASCII text Streams: binary For our assignments, we could either read binary strings and convert them to ASCII or we could simply use the provided writer classes We will use buffered connections for efficiency and coding elegance Buffers allow packets to be sent when a buffer is filled, not on a byteby-byte basis Buffers allow us to send an object to a I/O stream instead of a bit I/O Classes of Interest InputStreamReader Takes an input stream from an I/O port and interprets it as ASCII Sends an output stream to an I/O port as ASCII Takes in InputStream and adds useful methods and a buffer to the stream Takes an OutputStream and adds useful methods and an output buffer to the stream OutputStreamReader BufferedReader PrintWriter Sockets in Java Socket support is provided through: java.net.* import java.net.* We have 2 types of sockets we are interested in: ServerSocket class Socket class (client sockets) ServerSocket ServerSockets are the sockets used to poll a specific port for incoming connections Steps to using a ServerSocket 1. Create a new ServerSocket object ServerSocket ss = new ServerSocket(port); This requires blocking statement until a connection is received 2. Wait until a connection has been received 3. Upon receiving a connection request, a new socket must be opened Socket client = ss.accept(); Socket I/O Provided by the methods Socket.getInputStream() and Socket.getOutputStream() Can be used in conjunction with any other stream sub-class E.g. PrintWriter and BufferedReader Example Code for Socket I/O BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true); This could also be accomplished in 2 steps each; e.x.: InputStreamReader temp = new InputStreamReader(client.getInputStream())); BufferedReader in = new BufferedReader(temp); Using Socket I/O Once BufferedReader and PrintWriter objects are created, they are used with the following methods: <BufferedReaderObject>.readLine(); <PrintWriterObject>.println(String); Full Example of Streams BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()), true); in.readLine(); out.println("Hello"); in.close(); out.close(); client.close(); Parsing Arguments from the Command Prompt Arguments from the prompt are passed into your main method through the string array args args[] is an array of space separated Strings Strings are stored in the array from the leftmost argument to the rightmost Since each element of args is type String, you can't directly pass that value into your server for use Java has built in functions for converting data types Integer.parseInt(String) To convert from String to Int, the method to use is: String Parsing Can't test for String equality with if (string == "hello") Methods provided by Java to do String comparisons String.equals(String) case sensitive String.equalsIgnoreCase(String) case insensitive Try/Catch Statements Exceptions are a java element used for troubleshooting and catching conditions that could "break" a program e.x.: null-pointer exceptions, passing the wrong data type, etc. Useful around any code block with I/O, as that's where mistakes can be made The Java compiler enforces try/catch blocks in newer versions by default Try/Catch Statements Idea is: first you try to execute some code If it fails you get an exception instead of the program crashing Code in the catch block allows you to keep running the program, but deal with the error If it works you simply exit the try portion and continue executing the program Try/Catch Example BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in)); int string; try { string = keyIn.readLine(); System.out.print(string); } catch (Exception e) { System.out.print("That wasn't in Integer!"); } Exception Types Different classes and methods throw different exception types e.x.: PrintWriter(String, String) throws FileNotFoundException and UnsupportedEncodingException Can catch specific exceptions and execute different code based on them Can catch all exceptions simply with "catch (Exception e)" Using Exceptions in Lab 2 You can exceptions use to parse the argument entered for the port You should wrap your server's executable code itself either in a single or series of try statements to ensure it won't crash If it does, you should catch the exception and alert the system that the server crashed Other Useful Classes Classes that have date objects java.util.Calendar java.util.Date (partially depreciated) java.text.simpleDateFormat Hints You can either try parsing the first argument of args in main and passing in a port by hand into the server object; OR You can use 2 constructors for both cases (argument passed in and no argument) Use the Java API document if you aren't sure what you need or how to manipulate and object I don't care if you use depreciated Date types in this assignment Hints Look through the java.net.* and java.io.* packages Focus on SocketServer, Socket (and .accept()), BufferedReader, and BufferedWriter Look at the simpleDateFormat and Date classes Lab 2 Protocol-Code Structure getHead(): StringBuffer Easy: Loops through receiving data and appending it into a StringBuffer until the end of the header section is found What must be added to each line? getMethod(): String This parses the method out of the request. Easy to do, due to location of method in the Request Lab 2 Protocol-Code Structure getLenth(StringBuffer): int Why is this needed? Finds a String representing a number, parses it and returns it getBody(int): StringBuffer Uses a Integer to specify how many characters to read Must cast each byte you read() as a (char) getLength() Use String.indexOf(String) to find what you are looking for: String temp = new String("This is a test String for index"); int i = temp.indexOf("String"); i = 16 Now you know the start of the header you are looking for, but how do you find the value? Use a loop and iterate through with temp.charAt(i) until you find the end of the line as a character Use substring to parse only the section of string you want Use the same Integer.parseInt used in Assignment 1 getLength() //Find "for" int j; String temp = new String("This is a test String for index"); int i = temp.indexOf("String"); for(j=i+7;;j++){ if (!(temp.charAt(i)==' ')) j++; else break; } String answer = temp.substring(i+7, j); Why do we need the +7 for the index (i+7)? getBody() StringBuffer temp = new StringBuffer(""); for(i=0;i<length;i++){ temp.append((char)netIn.read()); } Why do we have to cast the input as (char)? Why can't we use readLine()? Threads We know a processor can only execute one program at a time One process may run at a time To run multiple programs (processes), the CPU must run one for a certain amount of time, save the state of the program, load another executing program and so on One program can have multiple modules that need to be execute "at the same time" for different functions. THREADS! Threads A parent process can spawn children A child...

Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Virgin Islands - SENG - 474
Instance Based LearningNearest Neighbor Remember all your data When someone asks a question Find the nearest old data point Return the answer associated with it In order to say what point is nearest, we have to define what we mean by &quot;near&quot;
Virgin Islands - SENG - 130
2a) SystemsIntroduction to Systems Introduction to Software SystemsRev. 2.02007 Scott Miller, University of Victoria 1 05/01/09What is a System? Collectionof 2 or more interrelated elements that work towards common purpose Natural; e.g. wea
Virgin Islands - LAW - 315
PROBLEM #9 EXISTENCE OF PARTNERSHIP AND PRIORITY OF CREDITORS Hubb had been the manager of a used car business which Cap, the owner, had sold several years earlier. Hubb decided to open his own lot in Victoria, B.C. and asked Cap if she would &quot;back&quot;
Virgin Islands - LAW - 345
Law 345 Taxation Spring 2004 Answers to Questions for Chapter 6 &quot;Profit&quot; and the Calculation of &quot;Profit&quot; 1. What is the starting point in s. 9(1) of the Income Tax Act for the determination of income from business or property?Section 9(1) says tha
Virgin Islands - LAW - 345
UNIVERSITY OF VICTORIA FACULTY OF LAW LAW 345 TAXATION SPRING 2004 MID-TERM TEST OPEN BOOK PART DATE: TIME: PLACE: Thursday, February 12, 2004 9:05 a.m. - 10:05 a.m. Room 157 Professor GillenThis test consists of 4 pages. Please check to be sure
Virgin Islands - LAW - 345
QUESTIONS FOR PART I INTRODUCTION &quot;TAX&quot; DEFINED AND TYPES OF TAXES 1. Provide a general definition of a tax and note the difficulty in identifying a &quot;tax&quot; by reference to at least two examples. Note also, by way of an example, that the definition ma
Virgin Islands - LAW - 315
PROBLEM #26 LIABILITY STRATEGIES AND SHAREHOLDER REMEDIES Joanne Mitch and Eve Miller were the daughters of Fred Menda. About three years ago Fred Menda had passed away. He had run various businesses and maintained various investments through Fred Me
Virgin Islands - CSC - 242
&gt; restart:with(plots):with(stats): iSeed:=48009341:# Warning, the name changecoords has been redefined&gt; randomize(iSeed):atrue:=0.5:btrue:=1.0:# We'll fit a set of bins to the function a*x+b. First we create the x# values, then the true y values
Virgin Islands - CSC - 242
&gt; restart:with(plots):with(stats):# Warning, the name changecoords has been redefined# You have two detectors that can measure the arrival time of a signal.# They are at positions (-60,0) and (60,0). The signal travels with a# speed of 5. The
Allan Hancock College - LGAFAB - 2003457
[Page Break] New South WalesLocal Government Amendment (NoForced Amalgamations) Bill 2003Contents Page 1 Name o
Virgin Islands - CSC - 242
Each year the Washington Post's Style Invitational asks readers totake any word from the dictionary, alter it by adding, subtracting, orchanging only one letter and supply a new definition. Here are the2002 winners:Intaxication: Euphoria at gett
Virgin Islands - CSC - 242
#!/usr/bin/perl# open file with text to unscramble$infile = $ARGV[0];# remove trailing line feedchomp($infile);open ( INFILE, &quot;&lt;$infile&quot; ) or die;# read contents into a local array, one line per array element@wisdom = &lt;INFILE&gt;;close INFILE;
Virgin Islands - LAW - 110
Fact pattern for Legal Analysis Exercise and AssignmentLaw 110: Legal Research and Writing September 25, 2006LEGAL ANALYSIS EXERCISE Facts Every year the grade 11 French students from Kelly's High School in Pleasantville B.C. travel to Quebec City
Virgin Islands - LAW - 110
The Canadian AbridgementLaw 110: Legal Research and WritingWhat is the Canadian Abridgment and What does it do? The Canadian Abridgment is a multi-volume research tool that provides: digests of cases organized by Subject Title, legal issue and sub
Virgin Islands - LAW - 110
FOR EDUCATIONAL USE ONLY 1972 CarswellOnt 476 [1972] 2 O.R. 437, 25 D.L.R. (3d) 661Moddejonge v. Huron (country) Board of Education Moddejonge et al. v. Huron County Board of Education et al. Ontario Supreme Court Pennell, J. Judgment: January 4, 1
Virgin Islands - LAW - 110
University of VictoriaDiana M. Priestly Law LibraryP.O. Box 2300, STN CSN Victoria, B.C. V8W 3B1 E-Mail: lawill@uvic.ca http:/library.law.uvic.ca Phone: 250-721-8565 Fax: 250-472-4174October 2008 SECONDARY RESOURCESBOOKS, GOVERNMENT DOCUMENTS,
Virgin Islands - LAW - 110
LAW 110: LEGAL RESEARCH AND WRITING 2005-2006 TO: FROM: DATE: RE: LRW Students Tim Richards November 10, 2005 Legal Memorandum No. 1 (&quot;Closed Memo&quot;)In addition to this set of instructions about the Closed Memo (worth 20%; due Nov 21st), please obta
Virgin Islands - LAW - 301
Search Franais Home Contact Us Important Notices Mailing Lists Advanced SearchCitation:C.U.P.E. v. Ontario (Minister of Labour), 2003 SCC 29, [2003] 1 S.C.R. 539 Date:May 16, 2003 Docket: 28396 Other formats: PDF WPDC.U.P.E. v. Ontario (M
Virgin Islands - LAW - 301
IN THE SUPREME COURT OF BRITISH COLUMBIACitation: McKenzie v. Minister of Public Safety and Solicitor General et al., 2006 BCSC 1372 Date: 20060908 Docket: L051335 Registry: VancouverRe: An Order of the Minister of Public Safety and Solicitor Gene
East Los Angeles College - CS - 223
Today's Lecture is in 3 PartsPart 1: The Project DoronPart 2: Going through the skipped over slides of last week's UML Overview lecture againAnandaPart 3: Tools AnandaCG152 Introduction: slide 1 CS223 The Project:Lecture 5 - Th
East Los Angeles College - CS - 223
Modellingwith UMLCS223 Lecture 4 (see BD Ch. 2) Ananda AmatyaNotice: Surgery Sessions (Weeks 6-10)Mon 2 - 4 in C1.01 &amp; Fri 9 - 11 in C1.04Please attend any one session convenient to youBernd Bruegge &amp; Allen H. Dutoit Object-Oriented Software
Virgin Islands - CSC - 571
Google's Map ReduceCommodity Clusters Web data sets can be very large Tens to hundreds of terabytes Cannot mine on a single server Standard architecture emerging: Cluster of commodity Linux nodes Gigabit Ethernet interconnect How to organi
Virgin Islands - CSC - 586
Notions of clustering Clustered file: e.g. store movie tuples together with the corresponding studio tuple. Clustered relation: tuples are stored in blocks mostly devoted to that relation. Clustering index: tuples (of the relation) with same searc
Virgin Islands - CSC - 212
Database Normalization Motivation Consider the following table in a RDBMS Show table. How many places would we have to change Dr. Coady's last name if it changed? NormalizationThe process by which we remove redundant data ins
Virgin Islands - LAW - 315
BENEFITS OF LIMITED LIABILITY 1. Valuation Costs 2. Monitoring Costs Unlimited Liabillity Need to Check -earning capacity (future cash flows) and risk -wealth of fellow investors Limited Liability Need to check -earning capacity (future cash flows) a
Virgin Islands - LAW - 329
SPP - (selling out our) Security, Prosperity (for Americans), (clearly not a) PartnershipIs this our plan?Is this what we mean by &quot;Security&quot;?Pipeline capacity 2000Environmental DisasterBig OilWe need a plan independence selfsufficie
Virgin Islands - LAW - 329
CEAAWHEN DOES IT APPLY? 1. is there a &quot;project&quot;? see defn in s. 2(1) [at p. 235 text] and Inclusion List Reg 2. is there a trigger? see s. 5 [p. 235} federal proponent federal money federal land ORon the Law List Reg3. do any exempti
Virgin Islands - LAW - 102
Review Session Questions: Law 102 November 5, 2007 Question 1: Constable Quick is told by a dispatcher that a street person (known to police as &quot;Joe&quot;) is unwittingly &quot;holding&quot; monies stolen in a taxicab robbery. The information provided to Quick is t
East Los Angeles College - CS - 411
Authoring of Adaptive HypermediaDr. Alexandra Cristeaa.i.cristea@warwick.ac.uk http:/www.dcs.warwick.ac.uk/~acristea/Bid for Topics for Coursework 2 Topics should be selected by Friday 18th, 12:00am Send one email per group to acristea@dc
Virgin Islands - LAW - 342
The Basics of Canadian Refugee LawInterpretation and ProofDefinition Person who a) by reason of a well-founded fear of persecution b) for reasons of race, religion, nationality, membership in a particular social group or political opinion c) i
East Los Angeles College - CS - 411
INTRODUCTION:This is a read-by-yourself exercise. We have learned about RDF, the Resource Description Framework. RDF is a directed, labeled graph data format for representing information on the web. The SPARQL query language has been promoted to the
East Los Angeles College - CS - 411
Coursework 2: Course topic selection, course content creation in MOT and initial labeling (30 marks/100; deadline: Friday 24th of October, 2008, 12:00am - extended to Monday 27th of October, 2008, 12:00am (extended due to clash with MEng project
Virgin Islands - LAW - 342
Immigration and Refugee Law 2008-9 Topic One: Historical and Global Context Case book (CB) Chapter One: pp.13-16 pp.16-23 pp.24-27 pp.32-39 Topic Two: Decisions and Decision Makers (Applications for Visa, Applications for Sponsorship, Provincial Nomi
Virgin Islands - LAW - 322
Family Law 322 Fall 2003 Chambers Assignment - Fact Pattern &quot;A&quot; = Victoria Registry No: 1116/03 BELINDA KORN, Plaintiff and MANDEEP BADYAAL, Defendant == This is Belinda's application under the Hague Convention on Civil Aspects of International Chil
Virgin Islands - LAW - 110
Fact Pattern CINTRODUCTIONTutorial Group 3The fact situation below will be used for Group 3, for the Open Memo, the Research Journal, the Summary of Argument and the Moot. The Memo and the Moots are essentially two parts of the same case. In the
Virgin Islands - LAW - 110
Law 110 - Legal Research &amp; WritingFall 2004Please read and compare these excerpts from the &quot;analysis&quot; portion of two legal memoranda in Jones v. Galleries International. Does one excerpt use techniques that give you, the audience, a better unders
East Los Angeles College - CS - 253
CS 253: Topics in Database Systems: C1Dr. Alexandra I. Cristea http:/www.dcs.warwick.ac.uk/~acristea/Lecturers Alexandra I. Cristea Hugh Darwen: hughdarwen@gmail.com Zabin Visram: zabin@dcs.warwick.ac.uk2Schedule Usual: Tue 14-15, B2.07/0
Virgin Islands - LAW - 326
The Employment RelationWho is an Employee? Predominant relation of production in capitalism is that of employer-employee For that reason, most of labour law is built on the platform of the contract of employment Definition of employee, therefore,
Virgin Islands - LAW - 326
Who is an Employee?Ballet Dancers: employees or independent contractors How to decide? What is test? What are factors? What is legal contextTests Control Montreal Locomotive 4 fold test Integration/ organization In business on won accoun
Virgin Islands - LAW - 502
GRADUATE SEMINAR IN APPLED LEGAL METHODOLOGY LAW 502 SPRING 2009 COURSE SYLLABUS Professor Judy Fudge All of the assigned readings are available on the course website, accessible at: http:/www.law.uvic.ca/NEW-Law-site/course_web_sites.php under Spr
Virgin Islands - LAW - 326
Employment LawWINTER, 2005 - INSTRUCTOR: J.A. FUDGE Note: This bibliography is selective, not exhaustive. It is also Ontario-centric. You should consult it for specific topics and issues as a starting place for your research. Happy reading! Ackroyd,
Virgin Islands - LAW - 343
Questions for Break out Groups Week 3 Advanced Laobur Law Please break into three groups. Each group should discuss the question specifically assigned to the group, and the two broader questions identified at the bottom. You should identify a reporte
Virgin Islands - LAW - 100
Minimum Wage Commission v. Bell Canada [1966] SCR 145 The defendant company is a national telephone company. Pursuant to a by-law enacted by virtue of the powers conferred upon it by the Minimum Wage Act, R.S.Q. 1941, c. 164, the Minimum Wage Commiss
East Los Angeles College - CS - 252
CS2520 UNIVERSITY OF WARWICK Department of Computer Science Second Year Summer Examinations 2007/08 Fundamentals of Relational Databases Time allowed: 1.5 hours This is a closed book exam. No information sources and communication devices are allowed.
East Los Angeles College - CS - 253
CS2530 UNIVERSITY OF WARWICK Department of Computer Science Second Year Examinations: Summer 2007 Topics in Database Systems MOCK EXAM FORM ONLY Time allowed: 2 hours Answer ALL questions in Section A (1,2,3), FOUR questions in Section B (out of 4,5,
Virgin Islands - LAW - 100
CONSTITUTIONAL LAW Fall 2007 and Spring 2008 Hester Lessard Office 237 Course Introduction 1. COURSE DESCRIPTION Tel: 721-8164 hlessard@uvic.caThis course examines the institutions, values, texts, practices and frameworks that together form the Can
Virgin Islands - LAW - 318
Reliance Damages Outline (reloutline.doc) Purpose: To compensate P for expenses rendered futile b/c of D's breach Restores P to position that s/he would have been in had wrong not occurred Includes wasted expenses and opportunity costs
Virgin Islands - LAW - 318
MAREVA INJUNCTION Definition: pretrial injunction restraining D and persons with control over D's assets from dealing with their assets in ways that will be detrimental to P's interests pending trial. Available where P has a strong prima facie case
Virgin Islands - CSC - 571
Distributed LockingDistributed Locking (No Replication)Assumptions Lock tables are managed by individual sites. The component of a transaction at a site can request locks on the data elements only at that site. Locking X It might seem that ther
Virgin Islands - LAW - 110
Law 110 Legal Research and Writing 2004-2005PUBLICATION OF JUDGMENTSHollis v. Dow CorningEach case is assigned a docket number by the Court Registry. The number appears on the judgment issued for that case. eg. File No.23776 As of 1999, courts
Virgin Islands - SENG - 474
Hierarchical Clustering Produces a set of nested clusters organized as a hierarchical tree Can be visualized as a dendrogram A tree like diagram that records the sequences of merges or splits0 .26 4 3 4 5 2 1 3 150 5 .120 .10 5 .00
Virgin Islands - CSC - 370
Entity-Relationship ModelDatabase Modeling The process of designing a database begins with: an analysis of what information the database must hold, and the relationships among components of that information. The structure of the database, called
Virgin Islands - CSC - 370
From E/R Diagrams to RelationsThe Relational Data ModelDatabase Model (E/R) Relational Schema Physical storageDiagrams (E/R)Tables: row names: attributes rows: tuplesComplex file organization and index structures.TerminologyAttri
East Los Angeles College - CS - 319
Relational Data Base Design in PracticeNormal Forms More about Anomalies Algorithms for Database Design05/01/091CS319 Theory of DatabasesDatabase Design Concepts Review 1A relational database scheme can be regarded as defined by an abstract
Virgin Islands - PE - 117
Game/Task Outline. Name of Activity:_ Tactical Problem: Skill development: Teaching Points Tactic progression: DiagramSkill progression:Biomechanical RemindersGame Aim and rules.AIM:Rules 1. 2. 3. ExtensionsTim HopperPage 15/1/2009
Virgin Islands - EDUC - 304
TASK PROGRESSION SHEET FOR CREATIVE DANCE LESSON IMAGERY IDEA Dance of the warriors Hunting a snake then tribal dance to celebrate. Grade 3 in pairs or Grade 4 in tribal groups. OBJECTIVES (TSWBA after lesson) Cognitive: Move with purpose in relation
East Los Angeles College - M - 117
Multiple InheritanceInheriting from more than one class is called multiple inheritance Some languages allow us to so this - C+ allows us to do this But Java doesn't Multiple inheritance What Java does is allow classes to extend (or
East Los Angeles College - M - 117
Books Teach yourself Java by Joseph O Neil McGraw Hill Fundamentals of programming using Java (p230.) Edward Currie Thomson Java Tutorials http:/webcem01.cem.itesm.mx:8005/web/java/tut Lecture 5 Outline Project Revise concepts obj
East Los Angeles College - M - 117
MA117 Programming for ScientistsJAVA skills: review primitive type variables: simple flow control statements (if, while,for . ) write and modify simple classes, understand instance methods and variables.Week 13JAVA files needed: see wepage for
Virgin Islands - UNITS - 452
Follow-the-Leader
Virgin Islands - LAW - 345
QUESTIONS FOR PART I INTRODUCTION &quot;TAX&quot; DEFINED AND TYPES OF TAXES 1. Provide a general definition of a tax and note the difficulty in identifying a &quot;tax&quot; by reference to at least two examples. Note also, by way of an example, that the definition ma