Computer Network File Socket Programming
Computer Network File Socket Programming
Socket Programming
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.
1. Establish a connection
2. Communication over socket
3. Closing the connection
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:
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;
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;
socket = server.accept();
System.out.println("Client accepted.");
} 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 -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:
Client Side:
Step - 1: Start.
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:
Step – 6: Display the message that is echoed back from the server. Step –
EchoServer.java
import java.io.*;
import java.net.*;
try
System.out.println(err);
try
while (true)
String line;
do
line = r.readLine(); if
( line != null )
}while ( !line.trim().equals("bye") );
client.close();
System.err.println(err);
EchoClient.java import
java.io.*; import
EchoClient
try
String line;
do
line = r.readLine();
if ( line != null )
System.out.println(line); line
= con.readLine(); w.println(line);
}
while ( !line.trim().equals("bye") );
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;
while (true) {
try {
s = server.accept();
}
catch (IOException ex) {
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
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;
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);
}
while (user.hasNext()) {
input = user.next(); // Hold the input from the user
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;
Page 58 of 68
try (Socket socket = new Socket("localhost", 900)) {
socket.getInputStream());
socket.getOutputStream());
System.out.println(
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
throws Exception
int bytes = 0;
FileInputStream fileInputStream
= new FileInputStream(file);
dataOutputStream.writeLong(file.length());
!= -1) {
dataOutputStream.write(buffer, 0, bytes);
Page 60 of 68
dataOutputStream.flush();
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 {
= new ServerSocket(900)) {
System.out.println(
System.out.println("Connected");
clientSocket.getInputStream());
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();
throws Exception
int bytes = 0;
Page 63 of 68
FileOutputStream fileOutputStream
= new FileOutputStream(fileName);
long size
buffer, 0,
(int)Math.min(buffer.length, size)))
!= -1) {
fileOutputStream.write(buffer, 0, bytes);
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
}
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
RemoteClient.java :
javac RemoteClient.java
java RemoteClient
Page 68 of 68