0% found this document useful (0 votes)
74 views14 pages

Chapter 4 Network Lab

The document describes code for a client-server application that allows a client to connect to a server and perform addition operations. The server code opens a port and accepts connection requests from clients. It reads integer values sent by the client, performs the addition, and sends the result back. The client code allows the user to enter two numbers, sends the request to the server, and displays the response. The client and server communicate over input/output streams using TCP sockets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views14 pages

Chapter 4 Network Lab

The document describes code for a client-server application that allows a client to connect to a server and perform addition operations. The server code opens a port and accepts connection requests from clients. It reads integer values sent by the client, performs the addition, and sends the result back. The client code allows the user to enter two numbers, sends the request to the server, and displays the response. The client and server communicate over input/output streams using TCP sockets.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

package network;

import java.util.Scanner;

import java.io.InputStreamReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.ServerSocket;

public class HelloServer

public static void main(String[] args)

String s;

Scanner inputStream;

PrintWriter outputStream;

ServerSocket serverSocket;

try

//Wait for connection on port 6789

System.out.println("Waiting for a connection.");

//bind to a port

serverSocket = new ServerSocket(6789);//bind to a port

Socket socket = serverSocket.accept();//listen for incomming data

//Connection made, set up streams

inputStream = new Scanner(new InputStreamReader(socket.getInputStream()));

outputStream = new PrintWriter(new DataOutputStream(socket.getOutputStream()));

//Read a line from the client


s = inputStream.nextLine();

//Output text to the client

outputStream.println("Well, ");

outputStream.println(s + " is a fine programming language!");

outputStream.flush();

System.out.println("Closing connection from " + s);

inputStream.close();

outputStream.close();

catch(IOException e)

//If any exception occurs, display it

System.out.println("Error " + e);

package network;

import java.util.Scanner;

import java.io.InputStreamReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.PrintWriter;

import java.net.Socket;

public class HelloClient

public static void main(String[] args)

String s;
Scanner inputStream;

PrintWriter outputStream;

try

// Connect to server on same machine, port 6789

Socket clientSocket = new Socket("localhost", 6789);

// Set up streams to send/receive data

inputStream = new Scanner(new InputStreamReader(clientSocket.getInputStream()));

outputStream = new PrintWriter(new DataOutputStream(clientSocket.getOutputStream()));

//send "Java" to the server

outputStream.println("Java");

outputStream.flush(); // Sends data to the stream

//Read everything from the server until no

// more lines and output it to the screen

while(inputStream.hasNextLine())

s = inputStream.nextLine();

System.out.println(s);

inputStream.close();

outputStream.close();

catch(IOException e)

System.out.println("Error " + e);

}
}

package network;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Date;

public class AdditionServer

public static void main(String[] args)

final int port = 8901;

// declare a "general" socket and a server socket

Socket connection;

ServerSocket listenSocket;

// declare low level and high level objects for input

InputStream inStream;

DataInputStream inDataStream;

// declare low level and high level objects for output

OutputStream outStream;

DataOutputStream outDataStream;
// declare other variables

String client;

int first, second, sum;

boolean connected;

while(true)

try

//create a server socket

listenSocket = new ServerSocket(port);//bind to a port

System.out.println("Server started at " + new Date());

System.out.println("Listening on port " + port);

// listen for a connection from the client

connection = listenSocket.accept(); //

connected = true;

System.out.println("Connection established");

// create an input stream from the client

inStream = connection.getInputStream();

inDataStream = new DataInputStream(inStream);

// create an output stream to the client

outStream = connection.getOutputStream ();

outDataStream = new DataOutputStream(outStream);

// wait for a string from the client

client = inDataStream.readUTF();//listen for incoming data

System.out.println("Address of client: " + client);

while(connected)

//read an integer from the client

first = inDataStream.readInt();
System.out.println("First number received: " + first);

// read an integer from the client

second = inDataStream.readInt();

System.out.println("Second number received: " + second);

sum = first + second;

System.out.println("Sum returned: " + sum);

// send the sum to the client

outDataStream.writeInt(sum);

catch (IOException e)

connected = false;

package network;

import java.io.InputStream;

import java.io.DataInputStream;

import java.io.OutputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Optional;
import javafx.application.Application;

import javafx.geometry.Pos;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.control.Label;

import javafx.scene.control.TextField;

import javafx.scene.control.TextInputDialog;

import javafx.scene.layout.HBox;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class AdditionClient extends Application

private String remoteHost;

private int port;

//declare low level and high level objects for input

private InputStream inStream;

private DataInputStream inDataStream;

//declare low level and high level objects for output

private OutputStream outStream ;

private DataOutputStream outDataStream;

//declare a socket

private Socket connection;

@Override
public void start(Stage stage)

getInfo(); // call the method that gets the information about the server

//declare visual components

TextField msg = new TextField();

TextField firstNumber = new TextField();

Label plus = new Label("+");

TextField secondNumber = new TextField();

Label equals = new Label("=");

Label sum = new Label();

Button calculateButton = new Button("Press to see the sum of the two numbers");

//configure the scene

msg.setMaxWidth(150);

firstNumber.setMaxWidth(30);

secondNumber.setMaxWidth(30);

HBox hBox = new HBox(10);

hBox.setAlignment(Pos.CENTER);

hBox.getChildren().addAll(firstNumber, plus, secondNumber, equals, sum);

VBox root = new VBox(10);

root.setAlignment(Pos.CENTER);

root.getChildren().addAll(hBox, msg, calculateButton);

Scene scene = new Scene(root, 400, 300);

stage.setScene(scene);

stage.setTitle("Addition Client");

// show the stage

stage.show();

try

{
//attempt to create a connection to the server

connection = new Socket(remoteHost, port);// connect to remote machine

msg.setText("Connection established");

// create an input stream from the server

inStream = connection.getInputStream();

inDataStream = new DataInputStream(inStream);

// create an output stream to the server

outStream = connection.getOutputStream();

outDataStream = new DataOutputStream(outStream);

// send the host IP to the server

outDataStream.writeUTF(connection.getLocalAddress().getHostAddress());//sending data

catch (UnknownHostException e)

msg.setText("Unknown host");

catch (IOException ie)

msg.setText("Network Exception");

// specifiy the behaviour of the calculate button

calculateButton.setOnAction(e ->

try

// send the two integers to the server

outDataStream.writeInt(Integer.parseInt(firstNumber.getText()));

outDataStream.writeInt(Integer.parseInt(secondNumber.getText()));

// read and display the result sent back from the server
int result = inDataStream.readInt();

sum.setText("" + result);

catch(IOException ie)

);

private void getInfo()

Optional<String> response;

//use the TextInputDialog class to allow the user to enter the host address

TextInputDialog addressDialog = new TextInputDialog();

addressDialog.setHeaderText("Enter remote host");

addressDialog.setTitle("Addition Client");

response = addressDialog.showAndWait();

remoteHost = response.get();

//use the TextInputDialog class to allow the user to enter port number

TextInputDialog portDialog = new TextInputDialog();

portDialog.setHeaderText("Enter port number");

portDialog.setTitle("Addition Client");

response = portDialog.showAndWait();

port = Integer.valueOf(response.get());

public static void main(String[] args)

launch(args);
}

package network;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

public class AdditionServerMultiple

public static void main(String[] args)

final int port = 8901;

AdditionServerThread thread;

Socket socket;

System.out.println("Listening for connections on port: " + port);

try

ServerSocket listenSocket = new ServerSocket(port);

while(true) // continuously listen for connections

socket = listenSocket.accept();

thread = new AdditionServerThread(socket);

thread.start();

catch(IOException e)

}
}

package network;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

public class AdditionServerThread extends Thread

private int id;

private static int totalConnections;

private final int port = 8901;

private final Socket connection;

private InputStream inStream;

private DataInputStream inDataStream;

// declare low level and high level objects for output

private OutputStream outStream;

DataOutputStream outDataStream;

// declare other variables

private String client;

private int first, second, sum;

private boolean connected;

public AdditionServerThread(Socket socketIn)


{

connection = socketIn;

@Override

public void run()

try

connected = true;

System.out.println("Connection established");

totalConnections++; // increase the total number of connections

id = totalConnections; // assign an id

//create an input stream from the client

inStream = connection.getInputStream();

inDataStream = new DataInputStream(inStream);

//create an output stream to the client

outStream = connection.getOutputStream ();

outDataStream = new DataOutputStream(outStream);

//wait for a string from the client

client = inDataStream.readUTF();

System.out.println("Address of client: " + client);

while(connected)

//read an integer from the client

first = inDataStream.readInt();
System.out.println("First number received from connection " + id + ": " + first);

//read an integer from the client

second = inDataStream.readInt();

System.out.println("Second number received from connection " + id + ": " + second);

sum = first + second;

System.out.println("Sum returned to connection " + id + ": " + sum);

// send the sum to the client

outDataStream.writeInt(sum);

catch(IOException e)

connected = false;

You might also like