Assignment 4
Assignment 4
Client-Side Program: A client can communicate with a server using this code.
This involves
1. Establish a Socket Connection
2. Communication
Java
import java.io.*;
import java.net.*;
import java.util.*;
// Client class
class Client {
// driver code
// number
// writing to server
socket.getOutputStream(), true);
BufferedReader in
socket.getInputStream()));
// object of scanner class
while (!"exit".equalsIgnoreCase(line)) {
line = sc.nextLine();
out.println(line);
out.flush();
+ in.readLine());
sc.close();
}
catch (IOException e) {
e.printStackTrace();
import java.io.*;
import java.net.*;
// Server class
class Server {
try {
server.setReuseAddress(true);
// client request
while (true) {
// requests
Socket client = server.accept();
// to server
+ client.getInetAddress()
.getHostAddress());
ClientHandler clientSock
= new ClientHandler(client);
// separately
new Thread(clientSock).start();
catch (IOException e) {
e.printStackTrace();
}
finally {
if (server != null) {
try {
server.close();
catch (IOException e) {
e.printStackTrace();
// ClientHandler class
// Constructor
this.clientSocket = socket;
}
BufferedReader in = null;
try {
clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String line;
// client
System.out.printf(
line);
out.println(line);
catch (IOException e) {
e.printStackTrace();
finally {
try {
if (out != null) {
out.close();
if (in != null) {
in.close();
clientSocket.close();
}
}
catch (IOException e) {
e.printStackTrace();
Steps:
Compile both Client and Server programs.
Run the server first and then the Client.
import java.io.*;
import java.net.*;
try {
// the next line will fail and drop into the catch block if
import java.io.*;
import java.net.*;
try {
+ server.getLocalPort());
System.err.println(ex);