0% found this document useful (0 votes)
16 views7 pages

Java Client-Server Programming Examples

The document contains multiple Java programs demonstrating client-server architecture, including displaying server date and time on the client, finding the primary IP address of a hostname, sending and displaying file contents, checking the existence of multiple files, and echoing messages until a termination command is received. Each program is structured with separate client and server classes, showcasing socket programming and data handling. The examples illustrate various networking concepts and error handling in Java.

Uploaded by

truptinik27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Java Client-Server Programming Examples

The document contains multiple Java programs demonstrating client-server architecture, including displaying server date and time on the client, finding the primary IP address of a hostname, sending and displaying file contents, checking the existence of multiple files, and echoing messages until a termination command is received. Each program is structured with separate client and server classes, showcasing socket programming and data handling. The examples illustrate various networking concepts and error handling in Java.

Uploaded by

truptinik27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Write a client-server program which displays the server machine’s date and time on the client
machine.
Solution:

Client code:
import [Link].*;
import [Link].*;
import [Link].*;

class s14q1Client
{
public static void main(String[] a)throws IOException
{
Socket st=new Socket("localhost",5917);
DataInputStream dis=new DataInputStream([Link]());
String d=[Link]()+"";
[Link]("date:"+d);
}

Server code:
import [Link].*;
import [Link].*;
import [Link].*;

class s14q1Server
{
public static void main(String[] a)throws IOException
{
ServerSocket st=new ServerSocket(5917);
Socket s= [Link]();
DataOutputStream dos=new DataOutputStream([Link]());
Date d=new Date();
[Link]("date:"+d);
[Link](d+"");
}

[Link] a program to find primary IP address of the host name which you passed as a parameter
import [Link].*;

public class OReillyByName {

public static void main (String[] args) {


try {
InetAddress address = [Link]("[Link]");
[Link](address);
} catch (UnknownHostException ex) {
[Link]("Could not find [Link]");
}
}
}

[Link] a program which sends the name of a text file from the client to server and displays the
contents of the file on the client machine. If the file is not found, display an error message.

server

import [Link].*;
import [Link].*;
import [Link].*;
class seta2serv
{
public static void main(String a[])
{
try
{
ServerSocket sc=new ServerSocket(4200);
[Link]("waiting for connection");
Socket s=[Link]();
[Link]("connection is established");
InputStream in=[Link]();
DataInputStream din= new DataInputStream(in);
String name=[Link]();
[Link]("File Name" +name);
OutputStream out=[Link]();
DataOutputStream dout=new DataOutputStream(out);
File f1=new File(name);
if([Link]())
{
String msg="",str="";
FileReader fr=new FileReader(name);
BufferedReader br=new BufferedReader(fr);
while((str=[Link]())!=null)
msg=msg+str+"\n";
[Link]("CONTENTS OF FILE:-\n"+msg);
}
else
[Link]("0");
}
catch(Exception e)
{
[Link]("Error="+e);
}
}
}

Client :

import [Link].*;
import [Link].*;

class seta2clin
{
public static void main(String a[])
{

try
{
Socket s=new Socket("localhost",4200);
BufferedReader br= new BufferedReader(new InputStreamReader([Link]));
[Link]("enter the file name is");
String name=[Link]();

OutputStream out=[Link]();
DataOutputStream dout=new DataOutputStream(out);
[Link](name);
InputStream in=[Link]();
DataInputStream din=new DataInputStream(in);
String msg=[Link]();
if([Link]("0"))
[Link]("file not found");
else
[Link](msg);

}
catch(Exception e)
{
[Link]("Error is:"+e);

}
}
}
[Link] a program to accept a list of file names on the client machine and check how many exist
on the server. Display appropriate messages on the client side.

import [Link].*;
import [Link].*;

class Slip10_Server
{
public static void main(String a[]) throws Exception
{
ServerSocket ss = new ServerSocket(1000);
[Link]("Server is waiting for client : ");
Socket s =[Link]();
[Link]("Client is connected");
DataInputStream dis=new DataInputStream([Link]());
DataOutputStream dos=new DataOutputStream([Link]());
while(true)
{
String fname =(String)[Link]();
if([Link]("End"))
{ break;

}
File f = new File(fname);
if([Link]())
{
[Link]("1");
}
else [Link]("0");
}
}
}
/* Client_Slip10_2 */

import [Link].*;
import [Link].*;

class Slip_Client
{
public static void main(String a[]) throws Exception
{
Socket s = new Socket("localhost",1000);
[Link]("client is connected : ");
DataInputStream dis=new DataInputStream([Link]());
DataOutputStream dos=new DataOutputStream([Link]());

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));


while(true)
{
[Link]("Stop proceesing enter End");
[Link]("Enter file name : ");
String fname = [Link]();

[Link](fname);
if([Link]("End"))
{
break;
}
String msg = (String)[Link]();
if([Link]("0"))
[Link]("File not present ");
else
{
[Link]("File Present");
//[Link](msg);
}
}
}
}

[Link] a server program which echoes messages sent by the client. The process continues till
the client types “END”.

import [Link].*;
import [Link].*;

class Server_Slip6_2
{
public static void main(String a[]) throws Exception
{
ServerSocket ss = new ServerSocket(1000);
[Link]("Server is waiting for client : ");
Socket s =[Link]();
[Link]("Client is connected");
DataInputStream ios=new DataInputStream([Link]());
DataOutputStream dos=new DataOutputStream([Link]());

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));


String s1,s2;
while(true)
{
s1 = (String)[Link]();
if([Link]("end") || [Link]("END"))
{
[Link]("chatting terminated");
break;
}
[Link]("Client "+s1);
[Link]("Server ...");
s2 = [Link]();
[Link](s2);
if([Link]("end") || [Link]("END"))
{
[Link]("chatting terminated");
break;
}
}
}
}
/*client_Slip6_2*/

import [Link].*;
import [Link].*;

class Client_Slip6_2
{
public static void main(String a[]) throws Exception
{
Socket s = new Socket("localhost",1000);
[Link]("client is connected : ");
DataInputStream ios=new DataInputStream([Link]());
DataOutputStream dos=new DataOutputStream([Link]());

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));


String s1,s2;
while(true)
{
[Link]("Server ....");
s1=[Link]();
[Link](s1);
s2=(String)[Link]();
if([Link]("end") || [Link]("END"))
{
[Link]("chatting terminated");
break;
}
[Link]("Client "+s2);
}
}
}

Common questions

Powered by AI

Potential issues include network latency causing delays in file transmission, server overloading if multiple clients request large files simultaneously, and the risk of transferring malicious files. These issues can be addressed by implementing load balancing, limiting file sizes, and scanning files for malware before allowing transmission. Additionally, using asynchronous I/O and optimizing buffer sizes could help mitigate latency issues .

The program can be optimized by processing filenames concurrently using multithreading or asynchronous I/O, which allows the server to check multiple files in parallel, thus reducing wait times. Caching could also be used to store frequently accessed file paths to eliminate redundant disk I/O operations. Additionally, employing a queue system can manage incoming requests more efficiently and avoid overwhelming server resources .

Socket programming allows a client and server to communicate over a network by establishing a connection through sockets, using IP addresses and port numbers to send and receive data. It provides a means for defining the protocol (e.g., TCP/UDP) used, which governs how data is transmitted and ensures both secure and efficient data exchange. This foundational approach underpins many network communication applications .

To enhance security, you could implement encryption protocols such as SSL/TLS to secure the transmission of data between the client and server. This would prevent potential eavesdroppers from intercepting and reading data. Additionally, implementing authentication mechanisms could ensure that only authorized clients can connect to the server, thus reducing the risk of unauthorized access .

Not handling exceptions properly can lead to server crashes, data corruption, or security vulnerabilities as unexpected states are not considered or logged. Mitigation involves implementing comprehensive exception handling logic that logs errors, notifies administrators, and gracefully degrades service or retries operations. This ensures the server remains operational and issues are addressed promptly without user impact .

User experience can be improved by providing a graphical user interface (GUI) that allows users to interact with the application more intuitively rather than using the command line. Implementing progress bars for file transfers, notifications for successful transfers, and estimated time of completion can enhance usability. Additionally, clear error messages and hints for troubleshooting common issues can further enhance user satisfaction .

The benefits of using TCP for the echo server include reliable data transmission, as TCP ensures packet delivery and maintains order, making it suitable for maintaining accurate message exchanges. Drawbacks include potential overhead from establishing and maintaining connections, which could impact performance in high-volume applications. TCP's reliability features can introduce latency, making it sometimes less suitable for real-time applications compared to UDP .

To support multiple clients simultaneously, the server can be modified to handle each client in a separate thread, essentially creating a thread pool to manage client connections concurrently. These threads could then share resources with thread-safe designs, such as using synchronized methods to avoid race conditions. Implementing a select-based model (non-blocking I/O) or using a framework like Java NIO could improve efficiency in managing multiple connections .

Not validating user input can lead to various security vulnerabilities such as SQL injection, buffer overflow, and remote code execution. These can allow attackers to access unauthorized data, crash the application, or execute harmful commands on the server. Ensuring input validation by sanitizing and filtering all inputs can mitigate these risks and protect the application from malicious exploitations .

Error handling can be improved by providing more descriptive error messages and implementing a retry mechanism. Instead of just printing an error message when an UnknownHostException occurs, you could log additional details such as the attempted hostname, timestamp, and possibly suggest corrective measures to the user, like checking network connection or correctness of the hostname .

You might also like