Unformatted text preview:

Java SocketsReading from and Writing to a Socket in JavaEcho ClientEcho Client descriptionEcho Client codeEcho Client code, cont’dEcho Client walkthroughEcho Client try blockechoSocket = new Socket("taranis", 7);Slide 10out = new PrintWriter (echoSocket.getOutputStream(), true);in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream()));Sending DataWhile LoopWhile Loop (continued)Slide 16HousekeepingSummaryThe BasicsWriting a Datagram Client and ServerDatagram Client / ServerThe QuoteServer ClassThe QuoteServerThread ClassSlide 24PortsSlide 26ConstructorRun MethodSlide 29Receive Request from ClientsDatagramPacketsocket.receive(packet);Server Responds to a RequestServer Response (continued)Server Sends ResponseSlide 36Server Sends Response (continued)Server Clean upThe QuoteClient ClassLocal VariablesProcess Command Line ArgumentsCreate SocketCreate Socket, cont’dClient Request to ServerSlide 45Slide 46Client Gets ResponseClient Gets Response (continued)getData MethodRunning the ServerRunning the ClientOutputMulti-Threaded Server Skeleton File: KKmultiServer.javaMain Server Skeleton File: KKmultiServer.java (continued)JAVA Classes for NetworkingURLURL ClassSlide 58URLConnection ClassServer Socket ClassInetAddress ClassSocket ClassMost common problem in Java - Setting EnvironmentApplet problemsJava SocketsSource:http://java.sun.com/docs/books/tutorial/networking/sockets/Reading from and Writing to a Socket in Java•Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.Echo Client•The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7.Echo Client description•EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server:Echo Client codeimport java.io.*;import java.net.*;public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); }Echo Client code, cont’dBufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));String userInput;while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine());}out.close();in.close();stdIn.close();echoSocket.close(); }}Echo Client walkthroughNote that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from the Echo server. Let's walk through the program and investigate the interesting parts.Echo Client try block•The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket: echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream()));echoSocket = new Socket("taranis", 7);•The first statement in this sequence creates a new Socket object and names it echoSocket. This Socket constructor requires the name of the machine and the port number to which you want to connect. This program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect.echoSocket = new Socket("taranis", 7);•The second argument is the port number. Port number 7 is the port on which the Echo server listens.out = new PrintWriter(echoSocket.getOutputStream(), true);•The second statement gets the socket's output stream and opens a PrintWriter on it.in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream()));•The third statement gets the socket's input stream and opens a BufferedReader on it. The example uses readers and writers so that it can write Unicode characters over the socket.Sending Data•To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter. To get the server's response, EchoClient reads from the BufferedReader. The rest of the program achieves this.While Loop•The while loop reads a line at a time from the standard input stream and immediately sends it to the server by writing it to the PrintWriter connected to the socket: String userInput;while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: "+in.readLine());}While Loop (continued)•The last statement in the while loop reads a line of information from the BufferedReader connected to the socket. The readLine method waits until the server echoes the information back to EchoClient. When readline returns, EchoClient prints the information to the standard output.While Loop (continued)•The while loop continues until the user types an end-of-input character. That is, EchoClient reads input from the user, sends it to the Echo server, gets a response from the server, and displays it, until it reaches the end-of-input. The while loop then terminates and the program continues, executing the next four lines of code: out.close(); in.close();


View Full Document

NJIT CS 602 - Java Sockets

Download Java Sockets
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Java Sockets and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Java Sockets 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?