Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Computer Network File Socket Programming

Uploaded by

21bit026
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Computer Network File Socket Programming

Uploaded by

21bit026
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Chapter-8

Socket Programming

Client-Side programming in Socket Example


First, a very important thing to understand is that there is a lot of low-level stuff that needs
to happen for performing such things but java.net is a networking package in Java that
takes care of all the things and it makes Java programming very easy for Java developers.

It may be the chance that you have a question about how to implement client-side
programming then don’t worried about it we will see all the basic things step by step.

Basically, we will do three main things client side:

1. Establish a connection
2. Communication over socket
3. Closing the connection

Establish a connection Client Side


Connecting with the other machines we need a socket connection first. Now, what is the
socket connection this is the question that arises here?

Socket connection simply means that two machines have information about each other
network location that is nothing but information about each other IP
Addresses and TCP ports. It is present inside the java.net package and below is the
complete package name of the Socket class in Java.

java.net.Socket
To start or open a socket in Java you need to write the below code:

Socket socket = new Socket("127.0.0.1",4999);


You can clearly see that there are two parameters while we open a socket. The first
parameter that is 127.0.0.1 is the IP address of localhost. Simply use the localhost address
here since here code will run on a single standalone machine.

The second parameter is the TCP port and it is just a number that simply represents which
application runs on a server. You can simply understand it as HTTP runs on port 80. Please
note port number can be from 0 to 65535.
Communication and Closing the connection
How we can communicate over a socket is the question that arises here? So, to
communicate over a socket connection we use the Streams for both input and output data.

And we can close the connection by simply sent the message to the server. In the below
example client keeps reading input from the user and sends those inputs to the server
until “Done” is typed.

ClientSideProgram.java

package com;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSideProgram {

//here we simply initialize socket, input & output streams

private Socket socket = null;


private DataInputStream input = null;
private DataOutputStream output = null;

//parametrized constructor for CilentSideProgram


public ClientSideProgram(String address, Integer port) {

//code to establish a connection


try {
socket = new Socket(address, port);
input = new DataInputStream(System.in);

// sends output to the socket


output = new DataOutputStream(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

String line = "";


//below line is to read message from input
while (!(line.equals("Done"))) {
try {
line = input.readLine();
output.writeUTF(line);
} catch (IOException e) {
e.printStackTrace();
}
}

//below code to close the connection


try {
input.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

public static void main(String[] args) {


ClientSideProgram clientProgram = new ClientSideProgram("127.0.0.1", 5000);
}
}
The above-given code is the client-side programming in Java Socket programming. Now
next is the server-side programming.

Server-Side Program in Java Socket Programming


Basically, server-side you require a two-socket for better communication with the client.
First socket for simply use for waiting for the client request whenever the client creates a
new Socket().

And a plain old socket which is used for communication with the client. And rest of the
steps are the same and socket side we used the getOutputStream() method for sending the
output through the socket.

Closing the connection concept is the same as the client-side programming. Below is the
client-side code.

ServerSideProgram.java

package com.javasocketprogramming;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSideProgram {

//initialize socket and input stream


private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;

// constructor with port


public ServerSideProgram(int port) {
// starts server and waits for a connection
try {
server = new ServerSocket(port);
System.out.println("Server started::");

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

socket = server.accept();
System.out.println("Client accepted.");

// takes input from the client socket


in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));

String line = "";

// reads message from client until "Done" is sent


while (!line.equals("Done")) {
try {
line = in.readUTF();
System.out.println(line);

} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Closing connection");

// close connection
socket.close();
in.close();
} catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
ServerSideProgram serverSideProgram = new ServerSideProgram(5000);
}

Output
Echo client and Echo server using TCP Sockets
Aim:
To write a Java program to implement Echo Client and Echo Server using TCP sockets.

Algorithm:

Server Side:
Step -1: Start.

Step -2: Import the necessary packages.

Step -3: Under EchoServer class, create a server socket to communicate with the client using
ServerSocket() constructor.

Step – 4: Accept the request from the client using accept() method.

Step – 5: Establish socket connection between client and server using BufferedReader. Step -6:

Echo the messages back to the client using PrintWriter() constructor.

Step – 7: Close the socket.

Client Side:
Step - 1: Start.

Step - 2: Import the necessary packages.

Step - 3: Under EchoClient class, create a new socket with IP address of the server system using
Socket() constructor.

Step – 4: Establish socket connection between client and server using BufferedReader. Step - 5:

Send messages to the server using getOutputStream() method.

Step – 6: Display the message that is echoed back from the server. Step –

7: Close the socket.


Program:

EchoServer.java

import java.io.*;

import java.net.*;

public class EchoServer

public EchoServer(int pno)

try

server = new ServerSocket(pno);

catch (Exception err)

System.out.println(err);

public void serve()

try

while (true)

Socket client = server.accept();

BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));


PrintWriter w = new PrintWriter(client.getOutputStream(), true);

w.println("Welcome to the Java EchoServer. Type 'bye' to close.");

String line;

do

line = r.readLine(); if

( line != null )

w.println("Got: "+ line);

}while ( !line.trim().equals("bye") );

client.close();

catch (Exception err)

System.err.println(err);

public static void main(String[] args)

EchoServer s = new EchoServer(9999); s.serve();

private ServerSocket server;


}

EchoClient.java import

java.io.*; import

java.net.*; public class

EchoClient

public static void main(String[] args)

try

Socket s = new Socket("10.10.16.41", 9999);

BufferedReader r = new BufferedReader(new


InputStreamReader(s.getInputStream()));

PrintWriter w = new PrintWriter(s.getOutputStream(), true);

BufferedReader con = new BufferedReader(new


InputStreamReader(System.in));

String line;

do

line = r.readLine();

if ( line != null )

System.out.println(line); line

= con.readLine(); w.println(line);

}
while ( !line.trim().equals("bye") );

catch (Exception err)

System.err.println(err);

Output:
Dictionary Server
The server:
package dictionaryserver;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

public class DictionaryServer {

public static void main(String[] args) throws IOException {

final int PORT = 8888;


final String FILE_NAME = "dictionary.txt";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
Scanner in = null;
PrintWriter out = null;
File inFile = null;
Scanner readFile = null;

while (true) {
try {
s = server.accept();
}
catch (IOException ex) {
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}

System.out.println("Accepted connection from client");

try {
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
inFile = new File(FILE_NAME); // The dictionary file
readFile = new Scanner(inFile); // Scanner which scans the file

Page 54 of 68
String input = null; // String holding the line taken from the file
while (in.hasNextLine()) {
String date = new Date().toString();
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
while (readFile.hasNextLine()) { // While there are unread lines in the file
System.out.println("nextline");
input = readFile.nextLine(); // Store the unread line
System.out.println("From the file " + input);
if (input.contains(temp)) { // If the read line contains the word sent from
the client
System.out.println("Check " + input + " " + temp);
out.println(date + " " + input); // Respond with the whole line
containing the meaning in the other language
out.flush();
}
else {
out.println("No knowledge for " + temp);
out.flush();
}
}
System.out.println("Received: " + temp);
}
}
catch (IOException ex) {
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");

out.close();
in.close();
System.exit(1);
}
out.close();
in.close();
}
}
}

Page 55 of 68
The client:
package dictionaryclient;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class DictionaryClient {

public static void main(String[] args) throws IOException {

final int PORT = 8888;


Socket s = null;
Scanner in = null;
PrintWriter out = null;

try {
s = new Socket("localhost", PORT);
in = new Scanner(s.getInputStream()); // Input stream from the server
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}

Scanner user = new Scanner(System.in); // Scanning for user input


String input;

while (user.hasNext()) {
input = user.next(); // Hold the input from the user

out.println(input); // Send it to the server


out.flush();

System.out.println("Response: " + in.nextLine());


}
Page 56 of 68
out.close();
in.close();
s.close();
}
}
The output from the server:

run:
Accepted connection from client
From the client exit
Received: exit

Page 57 of 68
File Transfer Server
File Transfer Implementation in Java Socket

In this example, we will create client.java class in this class we make the Socket object
and define the server socket port number for communication. In this class, we select
which file send over the network.
Client
To connect to another machine we need two pieces of information first one is the IP
address and the second one is the port number.
In our case, we are using localhost and the port is 900
We make a Socket object using the java.net package
Example
Socket ob = new Socket(ip,port _ number)
Now we call the “sendFile” method with the parameter of a file path and we open the file
and send the file to the server socket using DataOutputStream Class
Java

import java.io.*;

import java.net.Socket;

public class Client {

private static DataOutputStream dataOutputStream = null;

private static DataInputStream dataInputStream = null;

public static void main(String[] args)

// Create Client Socket connect to port 900

Page 58 of 68
try (Socket socket = new Socket("localhost", 900)) {

dataInputStream = new DataInputStream(

socket.getInputStream());

dataOutputStream = new DataOutputStream(

socket.getOutputStream());

System.out.println(

"Sending the File to the Server");

// Call SendFile Method

sendFile(

"/home/dachman/Desktop/Program/gfg/JAVA_Program/File Transfer/txt.pdf");

dataInputStream.close();

dataInputStream.close();

catch (Exception e) {

e.printStackTrace();

Page 59 of 68
// sendFile function define here

private static void sendFile(String path)

throws Exception

int bytes = 0;

// Open the File where he located in your pc

File file = new File(path);

FileInputStream fileInputStream

= new FileInputStream(file);

// Here we send the File to Server

dataOutputStream.writeLong(file.length());

// Here we break file into chunks

byte[] buffer = new byte[4 * 1024];

while ((bytes = fileInputStream.read(buffer))

!= -1) {

// Send the file to Server Socket

dataOutputStream.write(buffer, 0, bytes);

Page 60 of 68
dataOutputStream.flush();

// close the file here

fileInputStream.close();

Server
Here, we define the ServerSocket object using the ServerSocket class.
Example:
ServerSocket server = new ServerSocket(port_number)
when the client sent the request to the server socket. we will call the “receiveFile”
method
We receive the file from the client socket and read the file using the data input stream
class
In this method, we will change the file name and the location of the file. write the file
using FileOutputStream Class.
Java

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.FileOutputStream;

import java.net.ServerSocket;

import java.net.Socket;

Page 61 of 68
public class Server {

private static DataOutputStream dataOutputStream = null;

private static DataInputStream dataInputStream = null;

public static void main(String[] args)

// Here we define Server Socket running on port 900

try (ServerSocket serverSocket

= new ServerSocket(900)) {

System.out.println(

"Server is Starting in Port 900");

// Accept the Client request using accept method

Socket clientSocket = serverSocket.accept();

System.out.println("Connected");

dataInputStream = new DataInputStream(

clientSocket.getInputStream());

dataOutputStream = new DataOutputStream(

clientSocket.getOutputStream());

Page 62 of 68
// Here we call receiveFile define new for that

// file

receiveFile("NewFile1.pdf");

dataInputStream.close();

dataOutputStream.close();

clientSocket.close();

catch (Exception e) {

e.printStackTrace();

// receive file function is start here

private static void receiveFile(String fileName)

throws Exception

int bytes = 0;

Page 63 of 68
FileOutputStream fileOutputStream

= new FileOutputStream(fileName);

long size

= dataInputStream.readLong(); // read file size

byte[] buffer = new byte[4 * 1024];

while (size > 0

&& (bytes = dataInputStream.read(

buffer, 0,

(int)Math.min(buffer.length, size)))

!= -1) {

// Here we write the file using write method

fileOutputStream.write(buffer, 0, bytes);

size -= bytes; // read upto file size

// Here we received file

System.out.println("File is Received");

fileOutputStream.close();

Page 64 of 68
}

Output:

Page 65 of 68
Remote- Command Execution server
/* Implementation of Remote Command Execution using TCP */
// RemoteServer.java : A Simple Remote Server Program

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

class RemoteServer
{
public static void main(String args[])
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket ss=new ServerSocket(Port);
System.out.println(" Server is Ready To Receive a Command. ");
System.out.println(" Waiting ..... ");
Socket s=ss.accept();
if(s.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
BufferedReader buf=new BufferedReader(new
InputStreamReader(in));
String cmd=buf.readLine();
PrintWriter pr=new PrintWriter(ou);
pr.println(cmd);
Runtime H=Runtime.getRuntime();
Process P=H.exec(cmd);
System.out.println(" The " + cmd + " Command is Executed Successfully. ");
pr.flush();
pr.close();
ou.close();
in.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
Page 66 of 68
}

// RemoteClient.java : A Simple Remote Client Program

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

class RemoteClient
{
public static void main(String args[])
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
Socket s=new Socket("localhost",Port);
if(s.isConnected()==true)
System.out.println(" Server Socket is Connected Succecfully. ");
InputStream in=s.getInputStream();
OutputStream ou=s.getOutputStream();
BufferedReader buf=new BufferedReader(new
InputStreamReader(System.in));
BufferedReader buf1=new BufferedReader(new
InputStreamReader(in));
PrintWriter pr=new PrintWriter(ou);
System.out.print(" Enter the Command to be Executed : " );
pr.println(buf.readLine());
pr.flush();
String str=buf1.readLine();
System.out.println(" " + str + " Opened Successfully. ");
System.out.println(" The " + str + " Command is Executed Successfully. ");
pr.close();
ou.close();
in.close();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
Page 67 of 68
}
}

OUTPUT :

RemoteServer.java :

javac RemoteServer.java
java RemoteServer

Enter the Port Address : 1234


Server is Ready To Receive a Command.
Waiting .....
Client Socket is Connected Succecfully.
The calc Command is Executed Successfully.

RemoteClient.java :

javac RemoteClient.java
java RemoteClient

Enter the Port Address : 1234


Server Socket is Connected Succecfully.
Enter the Command to be Executed : calc
calc Opened Successfully.
The calc Command is Executed Successfully.

Page 68 of 68

You might also like