Client-Server Network Programming Session 2: Programming with Java and project

30
Client-Server Network Programming Session 2: Programming with Java and project A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science State University of New York at Fredonia

description

Client-Server Network Programming Session 2: Programming with Java and project. A workshop by Dr. Junaid Ahmed Zubairi Department of Computer Science State University of New York at Fredonia. Workshop Outline. Client-Server Mechanisms How the Applications work Introduction to sockets - PowerPoint PPT Presentation

Transcript of Client-Server Network Programming Session 2: Programming with Java and project

Page 1: Client-Server Network Programming Session 2: Programming with Java and project

Client-Server Network ProgrammingSession 2: Programming with Java and project

A workshop byDr. Junaid Ahmed ZubairiDepartment of Computer ScienceState University of New York at Fredonia

Page 2: Client-Server Network Programming Session 2: Programming with Java and project

Workshop Outline

1. Client-Server Mechanisms2. How the Applications work3. Introduction to sockets4. Socket types5.Programming with sockets6.Concurrent Processing7.Programming project

Page 3: Client-Server Network Programming Session 2: Programming with Java and project

Lab 2 Exercise 1

Take the client source code given earlier and compile and run itTry using the web server http://www.cia.gov and using the command GET /cia/publications/factbook/index.html HTTP/1.0

Page 4: Client-Server Network Programming Session 2: Programming with Java and project

Lab 2 Exercise 2

Modify the given client source code to conduct an SMTP dialogue with an email server such as “linus.cs.fredonia.edu”

Page 5: Client-Server Network Programming Session 2: Programming with Java and project

Lab 2 Exercise 3

Modify the given client source code to conduct communications with a time of day server and get and print the correct time from the server (NOTE: Use TCP port 13 and send a dummy message)

Page 6: Client-Server Network Programming Session 2: Programming with Java and project

Network Programming with Java Ref[4]

You can In Java, it is relatively easier to create a socket and connect it to a serverMake sure you import java.net.*Socket class is available for TCP sockets and DatagramSocket for UDP socketsYou can define objects that belong to pre-defined classes

Page 7: Client-Server Network Programming Session 2: Programming with Java and project

Java UDP Server

Step 1: Create a datagram socket on a specific portStep 2: Prepare buffer for receiveStep 3: Prepare datagram packet to receive data from clientStep 4: Receive datagram from clientStep 5: Extract client IP address and port number from the datagramStep 6: Prepare the response stringStep 7: Prepare the response packetStep 8: Send out the response(Compile and run UDPEchoServer.java [Ref 4] file as on the next slides)

Page 8: Client-Server Network Programming Session 2: Programming with Java and project

UDP Server: Initializing vars

import java.io.*;import java.net.*;

public class UDPEchoServer{

private static final int PORT = 1234;private static DatagramSocket

dgramSocket;private static DatagramPacket inPacket,

outPacket;private static byte[] buffer;

Page 9: Client-Server Network Programming Session 2: Programming with Java and project

Open Socket and call run( )

public static void main(String[] args){

System.out.println("Opening port...\n");try{

dgramSocket = new DatagramSocket(PORT);//Step 1.

}catch(SocketException e){

System.out.println("Unable to attach to port!");

System.exit(1);}run();

}

Page 10: Client-Server Network Programming Session 2: Programming with Java and project

Step 2 through 5

private static void run(){

try{String messageIn,messageOut;int numMessages = 0;do{buffer = new byte[256]; //Step 2.inPacket = new DatagramPacket(buffer, buffer.length); //Step 3.dgramSocket.receive(inPacket); //Step 4.InetAddress clientAddress =inPacket.getAddress(); //Step 5.

Page 11: Client-Server Network Programming Session 2: Programming with Java and project

Step 5 through 8

int clientPort =inPacket.getPort(); //Step 5.messageIn = new String(inPacket.getData(),0,inPacket.getLength());//Step 6.

System.out.println("Message received.");numMessages++;

messageOut = ("Message " + numMessages+ ": " + messageIn);

outPacket = new DatagramPacket (messageOut.getBytes(), messageOut.length(),clientAddress,clientPort); //Step 7.dgramSocket.send(outPacket); //Step 8.}while (true);}

Page 12: Client-Server Network Programming Session 2: Programming with Java and project

Catch Exceptions

catch(IOException e){e.printStackTrace();}

finally //If exception thrown, close connection.

{System.out.println("\n* Closing

connection... *");dgramSocket.close(); //Step 9.}

}}

Page 13: Client-Server Network Programming Session 2: Programming with Java and project

Java UDP Client

Step 1: Create a new datagram socketStep 2: Prepare new datagram packetStep 3: Send out the datagram to specified host and portStep 4: Prepare buffer for responseStep 5: Place the buffer in a packetStep 6: Use the packet to receive the response from serverStep 7: Close the socket(Obtain, compile and run UDPEchoClient.java [Ref 4] as on the next slides)

Page 14: Client-Server Network Programming Session 2: Programming with Java and project

Java UDP Client

import java.io.*;import java.net.*;

public class UDPEchoClient{

private static InetAddress host;private static final int PORT = 1234;private static DatagramSocket

dgramSocket;private static DatagramPacket inPacket,

outPacket;private static byte[] buffer;

Page 15: Client-Server Network Programming Session 2: Programming with Java and project

Simple main( ); calls run( )

public static void main(String[] args){

try{

host = InetAddress.getLocalHost();}catch(UnknownHostException e){

System.out.println("Host ID not found!");

System.exit(1);}run();

}

Page 16: Client-Server Network Programming Session 2: Programming with Java and project

Create a Socket and Try

private static void run(){try{dgramSocket = new DatagramSocket();//Step 1.

//Set up stream for keyboard entry...BufferedReader userEntry =new BufferedReader(new InputStreamReader(System.in));String message="", response="";

Page 17: Client-Server Network Programming Session 2: Programming with Java and project

If not the last one; form the out packet

do{System.out.print("Enter message: ");message = userEntry.readLine();if (!message.equals("***CLOSE***")){outPacket = new DatagramPacket(

message.getBytes(),message.length(),host,PORT);

Page 18: Client-Server Network Programming Session 2: Programming with Java and project

Steps 3 through 7

dgramSocket.send(outPacket); //Step 3.buffer = new byte[256]; //Step 4.inPacket = new DatagramPacket(

buffer, buffer.length); //Step 5.dgramSocket.receive(inPacket); //Step 6.response = new String(inPacket.getData(),

0, inPacket.getLength()); //Step 7.System.out.println("\nSERVER> " + response);

}}while (!message.equals("***CLOSE***"));}

Page 19: Client-Server Network Programming Session 2: Programming with Java and project

Exception Handling

catch(IOException e){e.printStackTrace();}finally{System.out.println("\n* Closing connection... *");dgramSocket.close(); //Step 8.}}}

Page 20: Client-Server Network Programming Session 2: Programming with Java and project

Lab3: Java Client and Server

Compile and run Java client and server. Obtain the Jcreator from http://www.jcreator.com/Download.htmTry to implement TCP client and server in Java

Page 21: Client-Server Network Programming Session 2: Programming with Java and project

Concurrent Processing

We should have some clear understanding of the terms processes and concurrency controlA process is a fundamental unit of computation that has an address space and at least one thread of execution

Page 22: Client-Server Network Programming Session 2: Programming with Java and project

Concurrent Processing

Concurrent processing means real or apparent simultaneous computing (by time sharing)On a shared network, many applications running on different machines may concurrently exchange messages. The network enforces bandwidth sharingA terminal server may offer concurrent connections to many clients otherwise its use is severely limited

Page 23: Client-Server Network Programming Session 2: Programming with Java and project

Concurrent Process Creation Example

#include <stdlib.h>#include <stdio.h>int sum;main() {int i;

sum=0;fork();for (i=1; i<=5; i++) {printf(“the value of i is %d\n”,i);fflush(stdout);sum+=i;}printf(“the sum is %d\n”, sum);exit(0);}

Page 24: Client-Server Network Programming Session 2: Programming with Java and project

Explanation

When the program reaches the line with statement fork(), the system duplicates the process and allows both the original and duplicate processes to execute forwardThe original process is called “parent” and the duplicate process is called “child”

Page 25: Client-Server Network Programming Session 2: Programming with Java and project

Parent-Child Identification

It is easy to identify who is parent and who is child. The value returned by fork() is examined. If it is zero, it is the child else it is the parentConsider the same program with the identification of parent and child

Page 26: Client-Server Network Programming Session 2: Programming with Java and project

Parent-Child Identification

#include <stdlib.h>#include <stdio.h>int sum;main() {int i;

sum=0;if (fork()) printf("This is parent\n");else printf("This is child\n");for (i=1; i<=5; i++) {printf(“the value of i is %d\n”,i);fflush(stdout);sum+=i;}printf(“the sum is %d\n”, sum);exit(0);}

Page 27: Client-Server Network Programming Session 2: Programming with Java and project

How to change the C server into concurrent program Ref [3]

Let the server accept an incoming connection and call a function to handle the request. Test your program to make sure it worksModify the code so that instead of calling the function, the server will spawn a new process with fork() or a new thread using pthreads. The new process or thread would handle the connection and exit. The server should stay in the following infinite loop:1. Wait for a connection request2. On receiving a new request, spawn a new process or

thread to handle the request3. Go back to step 1

Page 28: Client-Server Network Programming Session 2: Programming with Java and project

How to write concurrent Java server? Ref[4]

Use a support class called ClientHandler that extends class ThreadCreate a new object of this class and pass it the client socket as follows:ClientHandler Handler = new ClientHandler(client)Handler.start();Obtain and run MultiEchoServer.java and several copies of MultiEchoClient.java

Page 29: Client-Server Network Programming Session 2: Programming with Java and project

HW2: Programming Project

(Note: Design client and server completely either in C or Java. Clients and server may

run on the same machine. Submit all the source code.). UDP client sends a test message containing dummy text and message serial number followed by client ID to the server repeatedly. The number of times this message is sent is specified by the user. The concurrent UDP server receives the message and in response sends out its own small ack. message to the client copying the client ID and client message serial number. The client checks its time before sending the message and after receiving ack. message from the server. Once all messages have been processed, the client reports the AVERAGE approx. round trip time taken over all messages received and the total NUMBER of messages lost. Server must display the received message and client ID from the client AFTER ack. is transmitted. All source code must be submitted. Full test session data should be enclosed that involves at least two clients and one server.

Page 30: Client-Server Network Programming Session 2: Programming with Java and project

Help for C Programming

Sockets Programming Presentation: http://www.cs.fredonia.edu/~zubairi/spring2000/cs435/sockets.pdf Sockets programming sample code: http://www.cs.fredonia.edu/~zubairi/spring2000/cs435/inettime.c Sockets programming sample code: http://www.cs.fredonia.edu/~zubairi/spring2000/cs435/simple.zip or http://www.cs.fredonia.edu/~zubairi/spring2000/cs435/simple.tar. Other help: http://www.cs.fredonia.edu/~arnavut/classes/cs437/socket.doc You must give explanation for all the major steps in the code using comments..