part 2 - Computer and Information Sciences

Download Report

Transcript part 2 - Computer and Information Sciences

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
1. Client-Server Mechanisms
2. How the Applications work
3. Introduction to sockets
4. Socket types
5. Programming with sockets
6. Concurrent Processing
7. Programming project
Lab 2 Exercise 1
Take the client source code given earlier
and compile and run it
Try using the web server
http://www.cia.gov and using the
command GET
/cia/publications/factbook/index.html
HTTP/1.0
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”
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)
Network Programming with Java
Ref[4]
You can In Java, it is relatively easier to
create a socket and connect it to a
server
Make sure you import java.net.*
Socket class is available for TCP sockets
and DatagramSocket for UDP sockets
You can define objects that belong to
pre-defined classes
Java UDP Server
Step 1: Create a datagram socket on a specific
port
Step 2: Prepare buffer for receive
Step 3: Prepare datagram packet to receive
data from client
Step 4: Receive datagram from client
Step 5: Extract client IP address and port
number from the datagram
Step 6: Prepare the response string
Step 7: Prepare the response packet
Step 8: Send out the response
(Compile and run UDPEchoServer.java [Ref 4]
file as on the next slides)
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;
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();
}
Step 2 through 5
private static void run()
{
try
{
String messageIn,messageOut;
int numMessages = 0;
do
{
buffer = new byte[256];
inPacket = new DatagramPacket(
buffer, buffer.length);
dgramSocket.receive(inPacket);
InetAddress clientAddress =
inPacket.getAddress();
//Step 2.
//Step 3.
//Step 4.
//Step 5.
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);
}
Catch Exceptions
catch(IOException e)
{
e.printStackTrace();
}
}
}
finally //If exception thrown, close connection.
{
System.out.println("\n* Closing connection... *");
dgramSocket.close(); //Step 9.
}
Java UDP Client
Step 1: Create a new datagram socket
Step 2: Prepare new datagram packet
Step 3: Send out the datagram to specified host and
port
Step 4: Prepare buffer for response
Step 5: Place the buffer in a packet
Step 6: Use the packet to receive the response from
server
Step 7: Close the socket
(Obtain, compile and run UDPEchoClient.java [Ref 4]
as on the next slides)
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;
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();
}
Create a Socket and Try
private static void run()
{
try
{
dgramSocket = new DatagramSocket();
//Set up stream for keyboard entry...
BufferedReader userEntry =
new BufferedReader
(new InputStreamReader(System.in));
String message="", response="";
//Step 1.
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);
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***"));
}
Exception Handling
catch(IOException e)
{
e.printStackTrace();
}
finally
{
System.out.println("\n* Closing connection... *");
dgramSocket.close();
}
}
}
//Step 8.
Lab3: Java Client and Server
Compile and run Java client and server.
Obtain the Jcreator from
http://www.jcreator.com/Download.htm
Try to implement TCP client and server
in Java
Concurrent Processing
We should have some clear
understanding of the terms processes
and concurrency control
A process is a fundamental unit of
computation that has an address space
and at least one thread of execution
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 sharing
A terminal server may offer concurrent
connections to many clients otherwise its use
is severely limited
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);
}
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
forward
The original process is called “parent”
and the duplicate process is called
“child”
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 parent
Consider the same program with the
identification of parent and child
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);
}
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 works
Modify 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.
2.
3.
Wait for a connection request
On receiving a new request, spawn a new process or thread
to handle the request
Go back to step 1
How to write concurrent Java
server? Ref[4]
Use a support class called ClientHandler that
extends class Thread
Create 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
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.
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.zi
p or
http://www.cs.fredonia.edu/~zubairi/spring2000/cs435/simple.t
ar.
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..