Download presentation
Presentation is loading. Please wait.
1
CSCD 330 Network Programming
Spring 2012 Lecture 7 Socket Programming in Java UDP and Threads Reading: Chapter 2 and see Relevant Links Some Material in these slides from J.F Kurose and K.W. Ross All material copyright 1 1
2
Review Client/Server Programming
Firefox HTTP Port: 80 Review Client/Server Programming So far, Host has IP Address Network Layer identifier Every network “device” has this identifier Phone, Toaster, etc. Processes running on Hosts Assigned a port number Port numbers identify processes Some port numbers reserved System reserves these Other port numbers reserved for widely recognized processes
3
Review Client/Server Programming
Communication Between Client/Server Uses object, “Socket” Socket is the API between a program and the TCP/IP stack of the OS It has an input stream and an output stream built in to it Both the client and server define different ends of this socket Actual link to Java .net Package Link to Java .net Package API explained
4
TCP/IP Client/Server How this works in Java Server Socket
1. Binds socket to specific port number 2. Listens for incoming connections on that port 3. When connection attempted, it accepts connection, creates a regular socket for communication to client 4. Port number is different and selected by TCP/IP stack software
5
TCP/IP Client/Server Java Code for Server
Server socket listens on a port Java Code for Server ss = new ServerSocket (port); // Loop forever While (true) { // Get a connection Socket newSocket = ss.accept (); // Deal with the connection // .... } Inside loop waits for connection Creates a new socket object representing new connection What is not obvious is that the new connection is through a different port number
6
TCP/IP Client/Server Java code for Client, Send/Receive Data
// Create a socket for communicating with server Socket clientSocket = new Socket ("hostname", 6789); // Create data streams for communicating through the socket BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()); PrintWriter out = new PrintWriter (clientSocket.getOutputStream ()); System.out.println (in.readLine ()); // Print output to screen Create a client TCP socket, with host and port Then, create streams to send input and get it back from server
7
Java Package .NET Can look at the Java Package API Another Tutorial
Another Tutorial
8
Example of Server Creating Socket Object
Demo a Server that listens on a port for a connection, and creates a “socket” object for talking to client Has Ephemeral port numbers Can use telnet to play the role of a client Steps: 1. Start my Server: HelloServer 5555 2. telnet localhost 5555 I am running my server, HelloServer on 5555
9
UDP Socket Programming
10
UDP Socket Programming
UDP no real “connection” between client and server No handshaking Sender attaches IP address and destination port to each packet Server must extract IP address and port of sender from received packet, so answer can be sent back! Tansmitted data may be received Out of order Lost 10
11
UDP Summary No connection setup No open “pipe” as in TCP
Main Differences, TCP Each batch of bytes sent with attached address information No special ServerSocket class in java 11
12
UDP Summary Create a packet Mail is a lot like UDP
Push it out into the network through a socket Server accepts the packet addressed to him Mail is a lot like UDP Each letter needs the address of the destination Independent letters sent to the same address
13
Java Classes for UDP Datagrams for connectionless protocol
Two classes implement datagrams in Java: java.net.DatagramPacket java.net.DatagramSocket DatagramPacket is actual packet of information, an array of bytes, that is transmitted over the network. DatagramSocket is socket that sends and receives DatagramPackets across the network. Think of DatagramPacket as the letter and DatagramSocket as mailbox where letters are delivered Need both classes for UDP sockets 13
14
Java Classes for UDP DatagramPacket class provides programmer with two constructors. First for DatagramPackets that receives data Constructor needs Array to store the data Amount of data to receive Second is used for DatagramPackets that sends data Same information as before Plus destination address and port number 14
15
Java Classes for UDP DatgramSocket represents connectionless socket
It provides two constructors, 1. Programmer can specify a port OR 2. Allow system to randomly use a port Methods Two most important methods, send() and receive() Each takes an argument of a constructed DatagramPacket send() method Data in packet is sent to specified host and port receive() method Will block execution until a packet is received by underlying socket, then data copied into packet provided 15
16
UDP Clients and Servers are Similar
TCP Server ServerSocket establishes the server at a specific port number Socket then connects to the client on a separate port number, somewhat behind the scenes Client Socket is used to connect to server at a specific port number UDP Uses DatagramSocket to listen for client on specific port number Gets DatagramPacket with IP address and port number of client, uses this information for reply to client Uses DatagramSocket to send DatagramPacket to server on specific port number Gets answer from Server and saves in DatagramPacket
17
Sentence Capitalizer (Again) Example: Java client (UDP)
import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket Translate hostname to IP address using DNS 17
18
Example: Java client (UDP), cont.
Create datagram with data-to-send, length, IP addr, port DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } Send datagram to server Read datagram from server 18
19
Sentence Capitalizer (Again) Example: Java server (UDP)
import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram 19
20
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } Get IP addr port #, of sender Create datagram to send to client Write out datagram to socket End of while loop, loop back and wait for another datagram 20
21
I/O and Sockets
22
More on I/O and Sockets Move on and study Input/Output and then threads Study client-server programs Also, go over the Input/Output of Sockets Sockets – with threads Allow multiple clients in parallel 22
23
Details of Socket I/O New Example DailyAdviceServer
Server provides valuable advice to clients You connect as a client and it sends back the “advice of the day” Random selection of advice messages Still one client at a time For connection-oriented, what type of socket are we using? 23
24
Daily Advice Client/Server
I need Advice “You need to rethink that hairdo” Client Server
25
Algorithm for Daily Advice Client
Creates a socket to Advice Server Waits for Server to provide excellent advice Reads advice from server Prints advice to screen Quits
26
Socket I/O - Client What IP is this? Number is a what?
import java.io.*; import java.net.*; //The client public class DailyAdviceClient { public void go() { try { Socket s = new Socket(" ", 4200); InputStreamReader streamReader = new InputStreamReader(s.getInputStream()); BufferedReader reader = new BufferedReader(streamReader); String advice = reader.readLine(); System.out.println("Today you should: " + advice); reader.close (); } catch(IOException ex) { ex.printStackTrace(); } } // close go What IP is this? Number is a what? 26
27
Socket I/O - Client //Main method
public static void main(String[] args) { DailyAdviceClient client = new DailyAdviceClient(); client.go(); } 27
28
Socket I/O - Client Input InputStreamReader acts like a bridge between
low-level byte stream, getInputStream() and high-level character stream like BufferedReader InputStreamReader streamReader = new InputStreamReader(s.getInputStream()); Converts bytes to characters Then ..... 28
29
Details of Socket I/O - Client
Input Continued ... We chain high-level character stream like BufferedReader to the InputStreamReader to read buffered characters BufferedReader reader = new BufferedReader(streamReader); String advice = reader.readLine(); Chaining of input streams from server to client looks like … 29
30
Details of Socket I/O - Client
Chain of input from server to client Client InputStreamReader getInputStream Server BufferedReader Buffered Characters Characters Sockets input stream in bytes Characters are buffered Converted to characters Why do you want to use a Buffered Reader class? 30
31
Buffered Readers are Efficient
Reason to use buffered reader More efficient I/O Each time you read a character, must access the disk Buffered reader gets several characters at once. Explains I/O performance 1st_edition/html/JPIOPerformance.fm.html
32
Socket I/O - Server import java.io.*; import java.net.*;
public class DailyAdviceServer { String[] adviceList = {"Take smaller bites", "Go for the tight jeans. No they do NOT make you look fat.", "One word: inappropriate", "Just for today, be honest. Tell your boss what you *really* think", "You might want to rethink that haircut."}; public static void main(String[] args) { DailyAdviceServer server = new DailyAdviceServer(); server.go(); // Main Server code in this routine } 32
33
Socket I/O - Server What is this number? What does this do?
public void go() { try { ServerSocket serverSock = new ServerSocket (4200); while(true) { Socket sock = serverSock.accept(); PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); // select advice string writer.println(advice); writer.close(); // need THIS or flush() or never writes... System.out.println(advice); // Writes to screen too } } catch(IOException ex) { ex.printStackTrace(); } // close go What does this do? 33
34
Socket I/O - Server private String getAdvice() {
int random = (int) (Math.random() * adviceList.length); return adviceList[random]; } 34
35
Socket I/O - Server Output
Create a PrintWriter object gets chained to low-level socket output getOutputStream PrintWriter acts like its own bridge between character data and the bytes it gets from the Socket’s low-level output stream Can then write strings to the socket connection PrintWriter writer = new PrintWriter(sock.getOutputStream()); String advice = getAdvice(); writer.println(advice); //adds a newline to string 35
36
Socket I/O - Server Chain of output from server to client Server
getOutputStream Clien t PrintWriter “message …” Message is in characters Sockets output stream in bytes 36
37
Threads in Java 37
38
Threads in Java What is a thread? Separate thread of execution
Called from an existing program A java class, Thread represents a thread in Java Has a separate stack !!! Allows you to run separate processes from main thread Can do concurrency 38
39
Threads What does it mean to have more than one stack?
Get the appearance of having multiple things happen at once Execution is actually moving back and forth between stacks It might look like this … 39
40
Threads Main gets started, invokes Dog method
User starts a thread, cat Execution switches between main and user thread Active thread Active thread cat.go() Dog() run() main() User thread Main thread 40
41
Threads in Java Two Classes in Java Threads
Runnable – Interface Thread – Class from which a thread is declared You link these two together The actual thread and The run method that runs the thread Other Way to Create a Thread Extending the Thread class (java.lang.Thread) 41
42
Threads in Java Advice is to implement Runnable not Extend Thread class, why? Answer, if thread class is to be subclass of some other class, it can’t extend from the Thread class Java does not allow a class to inherit from more than one class ... Use Runnable interface to implement threads
43
Threads in Java What are the Advantages of Thread?
Multithreading several advantages over Multiprocessing Threads are lightweight compared to processes Threads share same address space and can share both data and code Context switching between threads is less expensive than between processes Cost of thread intercommunication relatively low than that of process intercommunication Threads allow different tasks to be performed concurrently
44
Single Threaded and Multi-threaded Process Models
45
Threads in Java How to Launch
Runnable interface makes a job runnable as a thread First create a runnable job Create a thread object and hand it a runnable job to work on Then, the thread is started Example Runnable linked to Thread Runnable threadJob = new MyRunnable (); Thread myThread = new Thread (threadJob); 45
46
Example Threads via Runnable
Thread uses the run() method of the runnable interface. Example below public class MyRunnable implements Runnable { public void run () { go (); } public void go () { doMore (); public void doMore (); System.out.println (“Top o’ the stack”); Runnable has one method, run() This is where you put the job the thread is supposed to run 46
47
Example Threads via Runnable
Example Continued class ThreadTester { public static void main (String[] args) { Runnable threadJob = new MyRunnable (); Thread myThread = new Thread(threadJob); myThread.start(); System.out.println (“back in Main”); } Pass the Runnable instance to thread constructor Start the new thread 47
48
Thread States Running! Thread t = new Thread (r); t.start();
Thread ready to run, runnable state Waiting to be selected for execution Thread selected to run and is the currently running thread Thread created but not started Once thread is runnable, can go back and forth between running, runnable and blocked 48
49
Threads The JVM thread scheduler is responsible for deciding who gets to run next You, have little control over the decision Blocked Threads Thread might be blocked for many reasons Examples Executing code to read from socket input stream, but no data to read Executing code told thread to sleep Tried to call a method but object was “locked” 49
50
Scheduling Threads Don’t base your program’s correctness on the scheduler working in a particular way Can’t control it or even predict the scheduler behavior Implementations are different with different JVM’s Compile and run previous code several times to see this Results will differ even on the same machine 50
51
Multiple Clients Original Problem
Need to handle multiple requests for service from a given server Without threads One client at a time, process each until done With threads Many clients, process one, move on and process another etc. 51
52
Threads and multiple clients
Same problem, DailyAdvice Server Now, Add threads so we can service multiple clients at once Everyone will have the benefit of having great advice to start their day 52
53
ServerSocket serverSock = new ServerSocket(4200); while(true) {
public void go() { try { ServerSocket serverSock = new ServerSocket(4200); while(true) { AdviceRequest request = new AdviceRequest (serverSock.accept()); Thread thread = new Thread (request); thread.start (); } } catch(IOException ex) { ex.printStackTrace(); } // close go AdviceRequest is our Runnable object Pass an extension of Runnable to thread constructor 53
54
Inside run, processRequest does all the work is the “job” to be run
final class AdviceRequest implements Runnable { Socket socket; public AdviceRequest (Socket socket) throws Exception { this.socket = socket; } // Implement the run method of the Runnable interface public void run() { try { processRequest (); } catch (Exception e) { System.out.println (e); private void processRequest () throws Exception { // Attach a PrintWriter to socket's output stream PrintWriter writer = new PrintWriter(this.socket.getOutputStream()); String advice = getAdvice(); writer.println(advice); writer.close(); // must have THIS or flush() or it never writes... System.out.println(advice); AdviceRequest implements the Runnable interface One method - run () Inside run, processRequest does all the work is the “job” to be run Gets output stream and sends advice to one client 54
55
Summary Brief coverage of sockets with threads
Should be enough for you to get started This example will be available to download Put links to code on the main class page We will be implementing ..... A multi-threaded Web Server!!!! Also, practice client-server in the lab Can read references in RelevantLinks for more information 55
56
Webserver assignment will allow practice of these ideas
Lots of fun!!!! 56
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.