5 Pages

ByteArrayDemo.java

Course: INFT 73334, Fall 2009
School: Allan Hancock College
Rating:
 
 
 
 
 

Word Count: 1009

Document Preview

Seven In /** Week previous tutorials, we have examined I/O streams, which are useful in dealing with files and connection-oriented services. Another form of communication uses packets of information. Datagram packets, for example, allow us to send data in small chunks, and have this data sent over the Internet. In this tutorial, we will look at a simple sender/receiver example, without any error-detection or...

Register Now

Unformatted Document Excerpt

Coursehero >> California >> Allan Hancock College >> INFT 73334

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.
Seven In /** Week previous tutorials, we have examined I/O streams, which are useful in dealing with files and connection-oriented services. Another form of communication uses packets of information. Datagram packets, for example, allow us to send data in small chunks, and have this data sent over the Internet. In this tutorial, we will look at a simple sender/receiver example, without any error-detection or retransmission. We will also look at the ByteArrayInputStream and ByteArrayOutputStream classes, which make it easy to convert from a data type (say a String), into an array of bytes. Java has support for datagrams, and allows us to send data over networks using UDP (User Datagram Protocol with the Internet at transport layer). We can represent packets by using the DatagramPacket class, and we can send/receive packets by using the DatagramSocket class. Both of these classes can be found in the java.net package. Part A Using the online documentation of Borland JBuilder, familiarize yourself with the DatagramPacket and DatagramSocket class. Look in particular at the constructors for datagram packets and datagram sockets . We must store our packet data as a byte array, and we may specify a port number for socket communcation. Part B Conversion of data to bytes can be a difficult task in any language. Java, however, makes it easy with the ByteArrayOutputStream and ByteArrayInputStream classes. Just like any other input or output stream, we have read and write methods. We'll be using the ByteArrayOutputStream, and ByteArrayInputStream classes in our datagram example, so it is important to understand how they work before attempting Part C & D. Examine the following application, which reads a line of text, and coverts the line into a sequence of bytes using ByteArrayOutputStream. Once we have an array of bytes, the program displays the numerical value of each byte. We will use a ByteArrayOutputStream in the next example, to covert text to bytes for transmission over a network. **/ import java.io.*; // // // ByteArrayDemo // // Demonstrates conversion of text to a byte array, using the // ByteArrayOutputStream class // // public class ByteArrayDemo { public static void main (String args[]) throws IOException { try { System.out.println ("Enter a line of text to be coverted to bytes :"); // Read a line of text from the user DataInputStream din = new DataInputStream (System.in); String line = din.readLine(); // Create a byte array output stream to create our byte array ByteArrayOutputStream bout = new ByteArrayOutputStream (); // Write each char out for (int i= 0; i < line.length(); i++) bout.write ( line.charAt(i) ); // Get our byte array byte[] barray = bout.toByteArray(); // Now display the byte value of each element of our // array, except the last for (int j= 0; j < barray.length-1; j++) System.out.print (barray[j] + ", "); // Display last element with a . rather than a , System.out.println (barray[barray.length-1] + "."); // Pause for user System.in.read(); } catch (Exception e) { System.out.println ("I/O error " + e); System.in.read(); } } } /** BPart C Type out the following example, and look in particular at how we place a string into a packet, send a packet to a remote host, and pause the application. Run this example, and it will attempt to send data to a receiver which listens to port 2000 of the local machine. Note : You will need to leave this program running when you run the receiver example Part in D import java.net.*; import java.io.*; // // // PacketSender // // Sends UDP datagrams to port 2000 of the local machine // // public class PacketSender { public static void main(String args[]) throws IOException { // Try .. catch any errors thrown try { // Socket allows us to send/receive data DatagramSocket senderSocket = new DatagramSocket(); // Datagram packet allows us to store data for sending DatagramPacket packet; // Get the local address for sending packets InetAddress localAddr = InetAddress.getLocalHost(); // Sequence number for packets int sequence_number = 1; // Repeat indefinitely for (;;) { // Create a string message, to send in our datagram String message = "I am packet number " + sequence_number; // Display sequence number System.out.println ("Sequence number " + sequence_number); // Increment sequence_number using ++ operator sequence_number++; // Convert our message to a byte array, using // ByteArrayOutputStream ByteArrayOutputStream bout = new ByteArrayOutputStream(); // For every character in message, write it to our byte array // output stream for (int index = 0; index < message.length(); index++) { // Get a character char tmpChar = message.charAt(index); // Write it to our byte array bout.write ( tmpChar ); } // Get our byte array byte[] array = bout.toByteArray(); // Now, create a packet that will be send to receiver on port 2000 packet = new DatagramPacket (array, array.length, localAddr, 2000); // Write packet to receiver using UDP senderSocket.send (packet); // Sleep for one second second, pausing to prevent // flooding receiver Thread.sleep (1000); } } catch (Exception e) { System.err.println ("Error : " + e); System.in.read(); } } } Part D Type out the following example, which listens for UDP packets on port 2000. Run the application from Part C, and then the following application, and you'll see data from one application being sent over the network to the other appplication. Note: You will need to make Part C running simultaneously when you run this example. import java.net.*; import...

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:

ECCD - MPAQUET - 1002
ArraysComp 1002/1402 Notes Adapted from Dr. J. MorrisonA Problem with Variables Single variables are restrictive Problem: We need to use 20, 200, or 2000 variables Example: Databases access huge amounts of dataSingle Variable SolutionSolution
Allan Hancock College - INFT - 73334
/* superd.c - main */#define_USE_BSD#include &lt;sys/types.h&gt;#include &lt;sys/param.h&gt;#include &lt;sys/socket.h&gt;#include &lt;sys/time.h&gt;#include &lt;sys/resource.h&gt;#include &lt;sys/errno.h&gt;#include &lt;sys/signal.h&gt;#include &lt;sys/wait.h&gt;#include &lt;netinet/in.h&gt;
UMBC - MATH - 101
TEST #4 MATH 101NAME: _ SCORE: _/50 This is a Take Home Test. You may not get help from any of the Math Lab tutors with any of the problems on this test. Show all your work for full credit. Marks for individual questions are given in brackets. 1.(3)
Allan Hancock College - INFT - 73334
/* TCPechod.c - concurrent TCP echo server * Usage: TCPechod [port] */#define_USE_BSD#include &lt;sys/types.h&gt;#include &lt;sys/signal.h&gt;#include &lt;sys/socket.h&gt;#include &lt;sys/time.h&gt;#include &lt;sys/resource.h&gt;#include &lt;sys/wait.h&gt;#include &lt;sys/errn
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Priority Queues1Priority Queues Increase-Key Insertion Maximum and Extract-Max Other Implementations2Mike JacobsonDepartment of Computer Science University of Calgary34Lecture #275Mike Jacobson (Univers
Allan Hancock College - INFT - 73334
/* sum.c - To see the effect of timeslicing on two concurrent processes, we give this example program in which each process runs for longer than the allotted timeslice. Each process sums integers from 1 to
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Heap Sort1Mike JacobsonDepartment of Computer Science University of Calgary 2HeapSort Description Correctness and EfciencyReferencesLecture #26Mike Jacobson (University of Calgary)Computer Science 331Lect
ECCD - COMP - 1402
Linked ListsCOMP 1002/1402Using Defined TypesData Structures are key to Computer Science Think of the JAVA libraries: Vector, ArrayList, Hashtable.1Lists of InformationBegin with a basic concept: A List Has a first element second element thi
Allan Hancock College - INFT - 73334
/* The program *//* To compile and run the program: cc -o back -Wall back.c ./back ls -l (or any other program)*/#include &lt;stdio.h&gt;#include &lt;sys/types.h&gt;#include &lt;stdlib.h&gt;#include &lt;unistd.h&gt;#include &lt;sys/wait.h&gt;int main(int argc, ch
Wilfrid Laurier - CPSC - 331
Outline1Computer Science 331Introduction to CPSC 3312Course Information Contact Information References Assessment Learning Goals Programming by Contract Algorithm Analysis and Testing Java Implementation Expected Background How to Succeed Read
ECCD - MATH - 0007
Introductory CalculusMATH 0007Review 1Examples:Page 1 October 20, 20041Functionsf (x) (or y = f (x) ) is an assignment x f (x) x y if you like) which, for each value of independent variable x from a certain set (the domain of denition of
Allan Hancock College - INFT - 73334
#include &lt;sys/types.h&gt;#include &lt;stdio.h&gt;#include &lt;sys/stat.h&gt;/* * Code to test if the first argument is a file or a directory * Usage: ./program file_to_test */int main(int argc, char *argv[]){ struct stat sb; int err; err = stat(arg
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Binary Heaps1Mike JacobsonDepartment of Computer Science University of Calgary 2Denition Binary Heaps Heap Shape Height Types of Heaps Representation ContinuationLecture #243Mike Jacobson (University of Calga
ECCD - MATH - 0007
Introductory CalculusMATH 0007Review 4Cosinecos x :Page 1 December 3, 20046SineTrigonometric Functionssin x :Tangenttan x :domain R range [-1, 1] x-intercepts at {k | k an integer} odd, 2 -periodic, continuous in Rdomain R range
Wilfrid Laurier - CPSC - 331
Outline1Denition Applications Implementations Array-Based Implementation (Circular Queues) List-Based Implementation Generalizations Double Ended Queues Priority Queues Queues in JavaComputer Science 331Queues Mike JacobsonDepartment of Comput
Allan Hancock College - INFT - 73334
/* TCPmechod.c - main, echo */#include &lt;sys/types.h&gt;#include &lt;sys/socket.h&gt;#include &lt;sys/time.h&gt;#include &lt;netinet/in.h&gt;#include &lt;errno.h&gt;#include &lt;unistd.h&gt;#include &lt;string.h&gt;#include &lt;stdio.h&gt;#defineQLEN 32/* maximum connection queue
ECCD - MATH - 0007
Introductory CalculusMATH 0007Review 3Example1 :nfor all FunctionsPage 1 November 19, 20045Curve Sketchingis an odd integer, thenEven and odd functions: even if f (-x) = f (x) f is odd f (-x) = -f (x)ofx from the domain fis symmetr
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Binary Search Trees Insertion and Deletion1BST Insertion BST Deletion Case 1 Case 2 Case 3 Case 4 Complexity Discussion References2Mike JacobsonDepartment of Computer Science University of CalgaryLecture #13
Allan Hancock College - INFT - 73334
/* The program *//* To compile and run the program: cc pulse.c -o pulse ./pulse(See output!)*/#include &lt;stdio.h&gt;#include &lt;signal.h&gt;#include &lt;unistd.h&gt;#include &lt;stdlib.h&gt;int main(void){ int pid1; int pid2; pid1 = fork();
Wilfrid Laurier - CPSC - 331
Outline1 2Computer Science 331Asymptotic NotationProperties and Application Types of Asymptotic Notation Big-Oh Notation Big-Omega Notation Big-Theta Notation Little-oh Notation Little-omega Notation Useful Properties and Functions Recommended
ECCD - MATH - 1005
MATH 1005C Test 3March 9, 2007 [Marks] [2] Questions 1-4 are multiple choice. Circle the correct answer. Only the answer will be marked. 1. [ln(n)]2 = n n lim (a) 0 (b) 1 (c) (d) 1 2 (e) Does not existSolution: (a) [2]2. The sequence {rn } conv
Allan Hancock College - INFT - 73334
/* Week 9 Java Network Programming Example 1: This simple server accepts one connection and then echoes everything received on that connection back to the sender. You may run it as the follows: &gt;java STServer &lt;port&gt; &amp; (say port is 3456
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Algorithms for Searching1The &quot;Searching&quot; Problem Unsorted Arrays Linear Search Sorted Arrays Linear Search Binary Search2Mike JacobsonDepartment of Computer Science University of Calgary 3Lecture #21Mike Jac
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Abstract Data Types, Interfaces, and the Java Collections Framework1Abstract Data Types and Interfaces Abstract Data Types Interfaces Java Collections Framework Introduction to the Java Collections Framework Notes on
Allan Hancock College - INFT - 73334
/* TCPtecho.c - main, TCPtecho, reader, writer, mstime */#include &lt;sys/types.h&gt;#include &lt;sys/param.h&gt;#include &lt;sys/ioctl.h&gt;#include &lt;sys/time.h&gt;#include &lt;sys/socket.h&gt;#include &lt;errno.h&gt;#include &lt;unistd.h&gt;#include &lt;stdlib.h&gt;#include &lt;string.
ECCD - MATH - 1005
1. Let f (x) = series of f .MATH 1005B - Solutions 60; 1; 2 x &lt; 0 0x2 , and f (x + 2) = f(x) for all x. Find the FourierThe Fourier series of f , with L = 2, is given by 1 nx nx i a0 X h + an cos + bn sin ; 2 2 2 n=1 with bn dx 2 2 0 nx
Wilfrid Laurier - CPSC - 331
Outline1 2Computer Science 331Stacks Mike JacobsonDepartment of Computer Science University of CalgaryDefinition Applications Parenthesis Matching Evaluation of Recursive Programs Implementation Array-Based Implementation Linked List-Based Imp
ECCD - MATH - 3057
MATH 30571Homework 3(due at 10:35 am on November 10, 2006) Problems 1-8 are on integration, Tylor and Laurent series. Special instructions: provide intermediate derivations. Problem 1. Compute (a)z 2 - 3|z| + Im z dz where (t) = 2eit , 0 t
Allan Hancock College - INFT - 73334
/* This program shows how to start a thread in an object byimplementing the Runnable interface. */public class ThreadDemo implements Runnable { protected Thread execution; public void begin () { if (execution = null) { execution =
Wilfrid Laurier - CPSC - 331
Outline1Computer Science 331Introduction to Red-Black Trees2Definition Definition and Example of a Red-Black Tree Implementation Details Height-Balance Black-Height of a Node The Main Theorem: Worst Case Height Bound First Lemma: Bounding Size
ECCD - MATH - 5406
Carleton University School of Mathematics and Statistics MATH 5406: Partial Dierential Equations Winter 2005 FINAL EXAMINATION Date: 13 April 2005; 14:0017:00 This is a closed book exam. Notes, books, etc are not allowed. No calculators allowed. Y
Allan Hancock College - INFT - 73334
/* Create a pipe, which has 2 ends: read end and write end. * Create 2 processes: parent and child. Child will read * from the reading end, parent will send stuff down the * writing end of the pipe. * * No arguments to this program. */#includ
Wilfrid Laurier - CPSC - 331
OutlineComputer Science 331Getting from Pseudocode to a Bound on Running Time1Objective and Strategy Running Time for Various Kinds of Programs A Single Statement A Sequence of Subprograms A Conditional Statement A Loop A Nested Loop A Simple
ECCD - MATH - 3057
MATH 30571Homework 1(due at 10:35 am on September 29, 2006) Problems 1-10 are on algebra of the complex plane; Problems 11-14 are on topology of the complex plane. Special instructions: provide intermediate derivations. Problem 1. Express the fo
Allan Hancock College - INFT - 73334
/* TCPmtechod.c - threaded echo server * * Usage: TCPechod [port] */#include &lt;unistd.h&gt;#include &lt;stdlib.h&gt;#include &lt;stdio.h&gt;#include &lt;string.h&gt;#include &lt;pthread.h&gt;#include &lt;sys/types.h&gt;#include &lt;sys/signal.h&gt;#include &lt;sys/socket.h&gt;#incl
East Los Angeles College - MJ - 665
Deriving Specifications from Requirements: an ExampleMichael Jackson AT&amp;T Bell Laboratories and MAJ Consulting Ltd 101 Hamilton Terrace London NW8 9QX England jacksonma@attmail.att.com mj@doc.ic.ac.uk Pamela Zave AT&amp;T Bell Laboratories Room 2B-413 M
Wilfrid Laurier - CPSC - 331
Outline1The Dictionary ADT Binary Trees Definition Additional Terminology Relationship Between Size and Depth Binary Search Trees Definition Searching Finding an Element with Minimal Key ExerciseComputer Science 331Binary Search Trees: Definiti
ECCD - MATH - 3057
MATH 30571Homework 4(due at 10:35 am on November 24, 2006) Problems 1-5 are on the residues and 6-8 are on conformal mappings. Special instructions: provide intermediate derivations. Problem 1. Compute the residues of (a) z2 at z0 = 0; sin2 z (b
Wilfrid Laurier - CPSC - 331
Computer Science 331 - Fall 2008 Assignment #3InstructionsThis assignment concerns lecture material that was introduced in this course on or before Friday,October 17. Please read the entire assignment before you begin work on any part of it. This
Allan Hancock College - INFT - 11135
Chapter 3Web TechnologyWeb PublishingStatic documents HTML, ASCII text, Postscript, PDF GIF, JPEG, MOV, Quicktime, AVI AU, WAV, MP3, RealAudio executable content Java, Javascript, Active-X, Dynamic HTML Dynamically-generated (on-the-fly) C
ECCD - MATH - 1005
MATH 1005 - 2003 Exam Solutions1. (d) 2. (b) 3. (a) 4. (c) 5. (c) 6. (d) 7. (b) 8. (b) 9. (e) 10. (a) 11. (e) 12. (b) 13. (d) 14. (b) 15. (b) 16. (a) 17. (c) 18. (b) 19. (b) 20. (c) 21. (b) 22. (e) 23. (c) 24. (e) 25. (e) 26. (c)2 27. (e) 28. (d)
ECCD - MATH - 1005
MATH 1005C Test 1January 26, 2007 NAME: [Marks] [5] 1. Solve the initial-value problem 2y = cos(x) , y(0) = -2. y ID#:[6]2. Solve the initial-value problem y =x2 + y 2 , y(-1) = 2. xy2 [6] 3. Find the general solution of xy + 3y = x + 1.[6
Allan Hancock College - INFT - 11110
Week 7A Breather + A Start on ObjectsHalfway Through We are halfway through the course! You now know the basics of programming: basic data types operators and expressions assignment statements selection statements: IF .. ELSE loops: WHILE
ECCD - MATH - 5406
MATH 54061Homework 2(due at 11:35 am on February 6, 2007) Problem 1. Find where the following equation is elliptic, hyperbolic and parabolic: (l + x)uxx + 2xyuxy y 2 uyy = 0, l R. Solution. The determinant a2 a1 a2 is 12 a2 12 a1 a2 = y (x +
Allan Hancock College - INFT - 11110
INFT11-110 Software Development 1 INFT71-110 Programming ConceptsDr. Warren Toomey Faculty of Information Technology 051What to expect from this subjectThis is a preparatory subject for a University degree in Information Technology:The subject
ECCD - MATH - 5406
MATH 54061Homework 1(due at 11:35 am on January 23, 2006) Problem 1. Integrate the following Cauchy problem for the rst-order equation ut + uux + u = 0, u(x, 0) = f (x). Solution. With the usual notation q = ut and p = ux , the equation is q +u(
Wilfrid Laurier - CPSC - 331
Computer Science 331 Solutions to Selected Tutorial #3 QuestionsQuestionsConsider the following code segment: / Pre-condition: A is a non-null array of integers / that contains at least one element / Post-condition: max is the largest element in t
Allan Hancock College - INFT - 11135
Chapter 0The Big PictureInternet History1969: ARPA R&amp;D projectpacket-switching network robust reliable vendor-independent decentralized operation1975: experimental-&gt;operationalInternet History (cont'd) 1983: tcp/ip milit
ECCD - MATH - 5406
MATH 54061Homework 3(due at 11:35 am on March 13, 2007) Problem 1. Solve the boundary/initial value problem u 2u = k 2 , 0 &lt; x &lt; L, t &gt; 0, t x u(0, t) = A, u(L, t) = B, t &gt; 0, u(x, 0) = f (x), 0 &lt; x &lt; L, where A and B are constants. Solution: B
Wilfrid Laurier - CPSC - 331
Outline1Computer Science 331Proofs of Correctness of Algorithms2Denition and Motivation Denition Motivation Parts of a Proof Partial Correctness Termination Strategy and Examples Strategy Important Cases ReferencesMike JacobsonDepartment of
Allan Hancock College - INFT - 11135
Chapter 2Application ProtocolsDomain Name Servicedefines a hierarchical naming standard for the Internettop-level-domains (TLDs) &quot;old-style&quot; .com, .edu, .net, .mil, .gov ccTLDs .au, .us, .gb rumsti.com, com.au second-level-domains
ECCD - MATH - 1005
MATH 1005B - Solutions 4Find the general solution: 1. y 00 + 2x(y 0 )2 = 0. Since y does not appear explicitly in the equation, let z = y 0 . Then y 00 = z 0 , and the equation becomes z 0 + 2xz 2 = 0, which is rst-order and separable. Thus, Z dx 1
Wilfrid Laurier - CPSC - 331
THE UNIVERSITY OF CALGARY FACULTY OF SCIENCEFINAL EXAMINATION COMPUTER SCIENCE 331WINTER SESSION: LECTURE 02 April 20, 2007 Time: 2 hrs.NAME: Please DO NOT write your ID number on this page.Instructions:Answer all questions in the space prov
ECCD - MATH - 3057
MATH 30571Name: ID#:Test 2(November 17, 2006) Problem 1. Find the integral of f (z): (a)f (z) = ez , from z = 1 to z = i. Does the value of the integral depend on the path? Ans: I = ei e1 = 1 e and does not depend on the path. (b)f (z) = |z|
Allan Hancock College - INFT - 11135
Network Access and Transmission MethodsTan Alam School of IT Bond UniversityLAN TopologiesPhysical Topology the physical/geographical layout of the network or segment. Logical Topology how information flows on the networkPhysical Bus Topolo
Wilfrid Laurier - CPSC - 331
CPSC 331 - Term Test #2 Solutions November 19, 2008Name:Please DO NOT write your ID number on this page.Instructions: Answer all questions in the space provided. Point form answers are acceptable if complete enough to be understood. No Aids Allo
ECCD - MATH - 1005
MATH 1005B - Notes 5 Systems of EquationsA system of two, linear, homogeneous equations with constant coecients has the form x0 = ax + by y 0 = cx + dy; where a; b; c and d are constants, and x and y are functions of t. The system may be expressed i
Wilfrid Laurier - CPSC - 331
CPSC 331 Term Test #1 February 12, 2007Name:Please DO NOT write your ID number on this page.Instructions: Answer all questions in the space provided. Point form answers are acceptable if complete enough to be understood. No Aids Allowed. There
Allan Hancock College - INFT - 11135
THE OSI &amp; TCP/IP MODELSTan Alam School of IT Bond UniversityThe OSI ModelLinkhttp:/topicmaps.bond.edu.au/mda/i nternet/osimodel/@/users/rho/InTechI/Physical LayerProtocols at this layer generate and detect voltage (or in the case of f
East Los Angeles College - ARTICLE - 216
#!/bin/sh# we have less than 3 arguments. Print the help text:if [ $# -lt 3 ] ; thencat &lt;HELPren - rename a number of files using sed regular expressionsUSAGE: ren 'regexp' 'replacement' files.EXAMPLE: rename all *.HTM files in *.html: ren
ECCD - MATH - 3057
MATH 3057: Functions of a Complex Variable Fall 2006 Instructor: Dr. Rouslan Krechetnikov Contact: Office: 2205 HP Phone: 520-2600, ext. 2141 E-mail: rkrechet@math.carleton.ca Office hours: TH 4:00-6:00 pm Website: http:/math.carleton.ca/~rkrechet/co