java-network代写: DA374A Network Applications

DA374A Network Applications Laboratory Exercise in Network Applications – I Transport Layer Programming and File I/O

IMPORTANT:

  • –  This is a mock lab/exercise. It is meant to help you prepare for the real lab on 18/11. You are

    NOT REQUIRED to submit anything for this.

  • –  Read and understand the sample programs attached to solve the given tasks. Completing

    this lab successfully is vital to pass Lab1.

  • –  Additional information will be given during the tutorial session.

Task1:
1a) Expand the TCP client and server programs (given at the end of this document) so that it can

be used for the following tasks:
Information Service: your server shall accept different requests/commands from the client and sends replies. These commands and their arguments look like the following:

Client-server programming.

TIME()
DATE() C2F(float temp) SUM(int [] list) QUIT

– Get server’s system time
– Get server’s system date
– Get temperature converted from centigrade to Farenheit . – The sum of integers in a list (e.g. SUM(2, 5, 9, 11, 20) = 47. – Disconnect client

1b) Repeat the above task using the UDP protocol based on the accompanying codes.

Task2: Server IO.
Suppose the server in Task 1a above stores files that are accessed from client machines. The clients connect to this server via a TCP socket and send the command for downloading a file by the given name located at the default (working) directory:

DLOAD(String filename) – Download the file from the server to the client
Implement the necessary code needed on both the Server and Client sides to perform this operation

using the APIs in the packages: 2a) java.io

2b) java.nio
A simple implementation for copying files locally is given in the last page of this document. Expand

the given code for copying (downloading) a source file located on a remote machine (server).

Compare and reflect on the performance of the two implementations. In order to make a good comparison, try downloading different file sizes such as 10KB, 100KB, 1MB, 10MB, 100MB, etc.

Modify the implementations in 2a for UDP.

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

public class TCPClient {
public static void main(String args[]) {

Socket client = null; int portnumber = 1234;

// Default port number we are going to use

/* A TCP CLIENT from Java Passion*/

if (args.length >= 1){
portnumber = Integer.parseInt(args[0]);

}

for (int i=0; i <10; i++) { try {

String msg = “”;

// Create a client socket
client = new Socket(InetAddress.getLocalHost(), portnumber);

System.out.println(“Client socket is created ” + client);

// Create an output stream of the client socket OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut, true);

// Create an input stream of the client socket InputStream clientIn = client.getInputStream(); BufferedReader br = new BufferedReader(new

InputStreamReader(clientIn));

// Create BufferedReader for a standard input
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));

System.out.println(“Enter your name. Type Bye to exit. “);

// Read data from standard input device and write it // to the output stream of the client socket.
msg = stdIn.readLine().trim();
pw.println(msg);

// Read data from the input stream of the client socket. System.out.println(“Message returned from the server = ” + br.readLine()); pw.close();
br.close();
client.close();

// Stop the operation
if (msg.equalsIgnoreCase(“Bye”)) {

break; }

} catch (IOException ie) { System.out.println(“I/O error ” + ie);

}}} }

/* SERVER – may have to be enhanced to work for multiple clients */

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

public class TCPServer {
public static void main(String [] args) {

ServerSocket server = null; Socket client;

// Default port number we are going to use int portnumber = 1234;
if (args.length >= 1){

portnumber = Integer.parseInt(args[0]); }

// Create Server side socket try {

server = new ServerSocket(portnumber);

} catch (IOException ie) { System.out.println(“Cannot open socket.” + ie); System.exit(1);

}
System.out.println(“ServerSocket is created ” + server);

// Wait for the data from the client and reply while(true) {

try {

// Listens for a connection to be made to
// this socket and accepts it. The method blocks until // a connection is made
System.out.println(“Waiting for connect request…”); client = server.accept();

System.out.println(“Connect request is accepted…”);
String clientHost = client.getInetAddress().getHostAddress();
int clientPort = client.getPort();
System.out.println(“Client host = ” + clientHost + ” Client port = ” + clientPort);

// Read data from the client
InputStream clientIn = client.getInputStream(); BufferedReader br = new BufferedReader(new

InputStreamReader(clientIn));

String msgFromClient = br.readLine();
System.out.println(“Message received from client = ” + msgFromClient);

// Send response to the client
if (msgFromClient != null && !msgFromClient.equalsIgnoreCase(“bye”)) {

OutputStream clientOut = client.getOutputStream(); PrintWriter pw = new PrintWriter(clientOut, true); String ansMsg = “Hello, ” + msgFromClient;

pw.println(ansMsg);

}

// Close sockets
if (msgFromClient != null && msgFromClient.equalsIgnoreCase(“bye”)) {

server.close(); client.close(); break;

}

} catch (IOException ie) {

} }

} }

import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;

/**
* @author meda

*/
public class UDPserver {

UDP Server

public static void main(String arg[]) throws Exception { DatagramSocket serversocket = new DatagramSocket(9999); byte[] receivedBuffer; // = new byte[1024];
byte[] sentBuffer; //= new byte[1024];
while (true) {

receivedBuffer = new byte[1024];
sentBuffer = new byte[1024];
DatagramPacket receivedpacket = new DatagramPacket(receivedBuffer, receivedBuffer.length); System.out.println(“Server Waiting for a message from Client…..”);

serversocket.receive(receivedpacket);
String fromClient = new String(receivedpacket.getData());

InetAddress clientIP = receivedpacket.getAddress();
System.out.println(“Message received from client : ” + fromClient + ” at IP Address = ” +

clientIP.getHostAddress() + “, Host Name = ” + clientIP.getHostName());

String toClient = “Hej Klienten! You said ” + fromClient;
sentBuffer = toClient.getBytes();
DatagramPacket sendpacket = new DatagramPacket(sentBuffer, sentBuffer.length, clientIP, 8888); serversocket.send(sendpacket);
System.out.println(” Reply Message is sent to client ” + clientIP.getHostAddress());

try{

Thread.sleep(2000); }

catch (InterruptedException ie ){}

} }

}

UDP Client

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;

/**
* @author meda

*/

public class UDPclient {

public static void main(String args[]) throws Exception { byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

BufferedReader inFromKeyboard = new BufferedReader(new InputStreamReader(System.in)); try {

DatagramSocket clientSocket = new DatagramSocket(8888); InetAddress IPAddress = InetAddress.getByName(“localhost”); while(true){

System.out.println(“Please enter the message to send to server: “); String sentence = inFromKeyboard.readLine();
sendData = sentence.getBytes();

DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9999); clientSocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

System.out.println(
“Message Sent to Server : ” + sentence + “\n Now waiting for reply from Server….”);

clientSocket.receive(receivePacket);

String fromServer = new String(receivePacket.getData());

System.out.println(“Message Returned from Server : ” + fromServer); }

}
catch (Exception e) {

e.printStackTrace(); }

} }

Example for copying files using Java IO and NIO

import java.io.*;
/** * * @author meda */
public class FileIO {
/*** * @param args the command line arguments     */
    static private void fileCopier(String source, String dest) {
        int n, i;
        long t;
        try {
            FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(dest);
            i=0;
            t = System.currentTimeMillis();
            while ( (n = fis.read()) != -1) {
               i++;
               fos.write(n);
            }
            t = System.currentTimeMillis() - t;
         fis.close();
         fos.close();
         System.out.println("File copy from " + source + " to
          " + dest + " is complete (" + i + " bytes.) in " + t
          + " milli sec.");
        }
        catch (IOException ioe ) {
            ioe.printStackTrace();
        }
        catch (FileNotFoundException fnfe) {
            System.err.println("File is not found");
        }

}

    public static void main(String[] args) {
        // TODO code application logic here
        String src = "somefile.src";
        String dst = "anotherfile.dst";
        fileCopier(src,dst);
    }

}