TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
Java networking programs socket based
1. Java – Networking Page 1
Java – Networking
PROGRAMS
Program 1: Write a program that obtains the IP address of a site.
/* Program to find the IP address of a website */
// Mukesh N Tekwani
import java.io.*;
import java.net.*;
class AddressDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a website name: ");
String site = br.readLine();
try
{
InetAddress ip = InetAddress.getByName(site);
System.out.print("The IP address is: " + ip);
}
catch(UnknownHostException e)
{
System.out.println("WebSite not found");
}
}
}
/* Output:
C:JavaPrgs>java AddressDemo
Enter a website name: www.google.com
The IP address is: www.google.com/74.125.235.50
*/
Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
2. 2 Java - Networking
Program 2: Write a program that connects to the home page of www.yahoo.com (read
from a URL).
//Program to connect to the home page of www.yahoo.com
// Mukesh N Tekwani
import java.net.*;
import java.io.*;
public class URLReader
{
public static void main(String[] args) throws Exception
{
URL myurl = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(new
InputStreamReader(myurl.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Output:
When this program is run, it displays the complete HTML code of the web page.
Possible Error: If we give site address simply as www.yahoo.com, we get MalformedURLException.
The protocol http must also be given in the complete URL.
Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
3. Java - Networking Page 3
Program 3: Write a program that parses a URL address into its components.
//Program to parse a URL address into its components
// Mukesh N Tekwani
import java.net.*;
import java.io.*;
public class ParseAddress
{
public static void main (String[] args)
{
if (args.length !=1)
{
System.out.println ("Error: missing url argument");
System.out.println ("Usage: java ParseURL <url>");
System.exit (0);
}
try
{
URL siteurl = new URL (args[0]);
System.out.println ("Protocol = " +
siteurl.getProtocol ());
System.out.println("Host = " + siteurl.getHost ());
System.out.println("File name= " + siteurl.getFile());
System.out.println("Port = " + siteurl.getPort ());
System.out.println("Target = " + siteurl.getRef ());
}
catch (MalformedURLException e)
{
System.out.println ("Bad URL = " + args[0]);
}
} // main
} // class ParseAddress
Output:
C:JavaPrgs>java ParseAddress http://www.microsoft.com
Protocol = http
Host = www.microsoft.com
File name =
Port = -1
Target = null
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
4. 4 Java - Networking
Program 4: Write a program to translate an IP address into host name or a host name to
an IP address.
// Translate IP address to hostname or vice-versa
// Mukesh N Tekwani
import java.net.*;
import java.io.*;
class TranslateAddress
{
public static void main (String args[])
{
if (args.length != 1)
{
System.out.println ("Error! No IP or host name
address");
System.out.println ("Usage: java TranslateAddress
java.sun.com");
System.out.println (" or java TranslateAddress
209.249.116.143");
System.exit (0);
}
try
{
// When the argument passed is a host name(e.g.
// sun.com), the corresponding IP address is returned.
// If passed an IP address, then only the IP address
// is returned.
InetAddress ipadd = InetAddress.getByName (args[0]);
System.out.println ("Address " + args[0] + " = " +
ipadd);
// To get the hostname when passed an IP address use
// getHostName (), which will return the host name
// string.
System.out.println ("Name of " + args[0] + " = " +
ipadd.getHostName ());
}
catch (UnknownHostException e)
{
System.out.println ("Unable to translate the
address.");
}
} // main
} // class TranslateAddress
/* Output:
C:JavaPrgs>java TranslateAddress 130.237.34.133
Address 130.237.34.133 = /130.237.34.133
Name of 130.237.34.133 = ns1.particle.kth.se
*/
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
5. Java - Networking Page 5
Program 5: Write a program to print all the addresses of www.microsoft.com
// Get all IP addresses by name of site
// Mukesh N Tekwani
import java.net.*;
public class AllAddressesOfMicrosoft
{
public static void main (String[] args)
{
try
{
InetAddress[] ipadd =
InetAddress.getAllByName("www.microsoft.com");
for (int i = 0; i < ipadd.length; i++)
{
System.out.println(ipadd[i]);
}
}
catch (UnknownHostException ex)
{
System.out.println("Could not find www.microsoft.com");
}
}
}
/*Output:
C:JavaPrgs>java AllAddressesOfMicrosoft
www.microsoft.com/64.4.31.252
www.microsoft.com/65.55.12.249
www.microsoft.com/65.55.21.250
www.microsoft.com/207.46.131.43
www.microsoft.com/207.46.170.10
www.microsoft.com/207.46.170.123
*/
Modification: Write a program that prints the Internet Address of the local host if we do not
specify any command-line parameters or all Internet addresses of another host if we specify the host
name on the command line.
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
6. 6 Java - Networking
Program 6: Write a program to obtain the IP address of the local machine.
// Find the IP address of the local machine
// Mukesh n Tekwani
import java.net.*;
public class MyOwnAddress
{
public static void main (String[] args)
{
try
{
InetAddress me = InetAddress.getLocalHost();
String myadd = me.getHostAddress();
System.out.println("My address is " + myadd);
}
catch (UnknownHostException e)
{
System.out.println("I'm sorry. I don't know my own
address; really lost!!!.");
}
}
}
/* Output:
C:JavaPrgs>java MyOwnAddress
My address is 192.168.1.7
*/
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
7. Java - Networking Page 7
Program 7: Write a program that accepts an IP address and finds the host name.
// Given the IP address, find the host name
// Mukesh N Tekwani
import java.net.*;
public class ReverseTest
{
public static void main (String[] args)
{
try
{
InetAddress ia =
InetAddress.getByName("65.55.21.250");
System.out.println(ia.getHostName());
System.out.println(ia);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
/* Output:
C:JavaPrgs>java ReverseTest
wwwco1vip.microsoft.com
wwwco1vip.microsoft.com/65.55.21.250
*/
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
8. 8 Java - Networking
Program 8: Write a program to download a file from the Internet and either copy it as a
file on the local machine or display it on the screen.
// Program-download a file & copy it as a file or display it on screen
// Mukesh N Tekwani
import java.io.*;
import java.net.*;
public class DownLoadFile
{
public static void main(String args[])
{
InputStream in = null;
OutputStream out = null;
try
{
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong no. of
arguments");
URL siteurl = new URL(args[0]);
in = siteurl.openStream();
if(args.length == 2)
out = new FileOutputStream(args[1]);
else
out = System.out; //display on client machine
byte [] buffer = new byte[4096];
int bytes_read;
while((bytes_read = in.read(buffer)) != -1)
out.write(buffer, 0, bytes_read);
}
catch (Exception ex)
{
System.out.println(ex);
}
finally
{
try
{
in.close(); out.close();
}
catch (Exception ae)
{
System.out.println(ae);
}
}
}
}
/* Output:
C:JavaPrgs>java DownLoadFile http://www.yahoo.com test.txt
*/
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
9. Java - Networking Page 9
CLIENT-SERVER PROGRAMS (Using Sockets)
Client Server
Create TCP Socket Create TCP Socket
Socket cs = new ServerSocket ss = new
Socket(hostname, port); ServerSocket(port);
Client initiates the communication Wait for client connection
by reading the user input Socket listen_socket =
Str = ss.accept();
userinput.readLine(); Then reads the client on listen_socket.
Then sends it to server Server listens client
Server_out.writeBytes(str client_str =
+ ‘n’); client_input.readLine();
Client listens to server using client Server sends reply to client
socket
Close client socket
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
10. 10 Java - Networking
Program 9: Write a client/server program in which a client sends a single string to the
server. The server just displays this string. (Echo)
Server Program:
//Server Program
//Works with file Client1
//Mukesh N Tekwani
import java.io.*;
import java.net.*;
class Server1
{
public static void main(String args[]) throws Exception
{
//create server socket
ServerSocket ss = new ServerSocket(4444);
while (true)
{
Socket listen_socket = ss.accept();
BufferedReader client_input = new BufferedReader(new
InputStreamReader(listen_socket.getInputStream()));
String client_str; //to store string rcvd from client
client_str = client_input.readLine();
System.out.println(client_str);
}
}
}
Client Program:
//Client Program
//Works with file Server1
//Mukesh N Tekwani
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String args[]) throws Exception
{
//create client socket
Socket cs = new Socket("localhost", 4444);
BufferedReader user_input = new BufferedReader(new
InputStreamReader(System.in));
DataOutputStream server_out = new
DataOutputStream(cs.getOutputStream());
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
11. Java - Networking Page 11
String str;
str = user_input.readLine();
server_out.writeBytes(str + 'n');
cs.close();
}
}
Program : Write a TCP/IP client / server program that sends a string in lowercase to the
server which sends the equivalent uppercase string back to the client.
Server Program:
//The server code Server.java:
import java.io.*;
import java.net.*;
public class ServerLower
{
// the socket used by the server
private ServerSocket serverSocket;
ServerLower(int port) // server constructor
{
/* create socket server and wait for connection requests */
try
{
serverSocket = new ServerSocket(port);
System.out.println("Server waiting for client on port " +
serverSocket.getLocalPort());
while(true)
{
Socket socket = serverSocket.accept();
System.out.println("New client asked for a
connection");
TcpThread t = new TcpThread(socket);
System.out.println("Starting a thread for a new
Client");
t.start();
}
}
catch (IOException e)
{
System.out.println("Exception on new ServerSocket:" + e);
}
}
public static void main(String[] arg)
{
new ServerLower(4444);
}
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
12. 12 Java - Networking
/** One instance of this thread will run for each client */
class TcpThread extends Thread
{
Socket socket; // the socket where to listen/talk
ObjectInputStream Sinput;
ObjectOutputStream Soutput;
TcpThread(Socket socket)
{
this.socket = socket;
}
public void run()
{
/* Creating both Data Streams */
System.out.println("Thread trying to create Object
Input/Output Streams");
try
{
// create output first
Soutput = new
ObjectOutputStream(socket.getOutputStream());
Soutput.flush();
Sinput = new
ObjectInputStream(socket.getInputStream());
}
catch (IOException e)
{
System.out.println("Exception creating new
Input/output Streams: " + e);
return;
}
System.out.println("Thread waiting for a String from the
Client");
// read a String (which is an object)
try
{
String str = (String) Sinput.readObject();
str = str.toUpperCase(); //convert lower 2 uppercase
Soutput.writeObject(str);
Soutput.flush();
}
catch (IOException e)
{
System.out.println("Exception reading/writing
Streams: " + e);
return;
}
catch (ClassNotFoundException e1)
{ //nothing needed here
}
finally
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
13. Java - Networking Page 13
{
try
{
Soutput.close();
Sinput.close();
}
catch (Exception e2)
{ //nothing needed here
}
}
}
}
}
Client Program:
//The client code that sends a string in lowercase to the server
import java.net.*;
import java.io.*;
public class ClientLower
{
ObjectInputStream Sinput; // to read the socker
ObjectOutputStream Soutput; // towrite on the socket
Socket socket;
// Constructor connection receiving a socket number
ClientLower(int port)
{
try
{
socket = new Socket("localhost", port);
}
catch(Exception e)
{
System.out.println("Error connectiong to server:" + e);
return;
}
System.out.println("Connection accepted " +
socket.getInetAddress() + ":" + socket.getPort());
/* Creating both Data Streams */
try
{
Sinput = new ObjectInputStream(socket.getInputStream());
Soutput = new
ObjectOutputStream(socket.getOutputStream());
}
catch (IOException e)
{
System.out.println("Exception creating I/O Streams:"+ e);
return;
}
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
14. 14 Java - Networking
String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";
// send the string to the server
System.out.println("Client sending "" + test + "" to
server");
try
{
Soutput.writeObject(test);
Soutput.flush();
}
catch(IOException e)
{
System.out.println("Error writting to the socket: " + e);
return;
}
// read back the answer from the server
String response;
try
{
response = (String) Sinput.readObject();
System.out.println("Read back from server: " + response);
}
catch(Exception e)
{
System.out.println("Problem reading back from server: " + e);
}
try
{
Sinput.close();
Soutput.close();
}
catch(Exception e)
{ // nothing needed here
}
}
public static void main(String[] arg)
{
new ClientLower(4444);
}
}
Modifications:
1. Modify the Server program in this example so that it is not multithreaded.
2. Modify the client program so that the input string is entered by the user from keyboard when program
runs, instead of storing it within the program.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
15. Java - Networking Page 15
Program 17:
Write a client-server socket application in which
(i) A client reads a character from the keyboard and sends the character out of its
socket to the server.
(ii) The server reads the character from its connection socket
(iii) The server finds the ASCII value of the character.
(iv) The server sends the ASCII value out of its connection socket to the client.
(v) The client reads the result from its socket and prints the result on its standard
output device.
Server Program:
//Server sends the ASCII code of a character to client
//Mukesh N Tekwani
import java.io.*;
import java.net.*;
class ServerASCII
{
public static void main(String args[]) throws Exception
{
String clientstr, serverstr;
ServerSocket ss = new ServerSocket(4444);
while(true)
{
Socket cs = ss.accept();
System.out.println("Connected to client...");
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(cs.getOutputStream());
clientstr = inFromClient.readLine();
//read the first character from input
char c = clientstr.charAt(0);
/* Find the ASCII code; note the type casting */
serverstr = "The ASCII code of " + clientstr + " is " +
(int)c + 'n';
outToClient.writeBytes(serverstr);
}
}
}
Output at Client end:
C:JavaPrgs>java ClientASCII
Enter a character
B
From server: The ASCII code of B is 66
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
16. 16 Java - Networking
PORTS AND SOCKETS
Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be intended for different
applications running on the computer. So how does the computer know to which application to forward the
data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that port.
A client can then rendezvous with the server at the server's port, as illustrated here:
Definition: The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer.
In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers
ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP
and other system services. These ports are called well-known ports. Your applications should not attempt to
bind to them.
Understanding Sockets
In client-server applications, the server provides some service, such as processing database queries or sending
out current stock prices. The client uses the service provided by the server, either displaying database query
results to the user or making stock purchase recommendations to an investor. The communication that occurs
between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the
client side in the same order in which the server sent it.
Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
17. Java - Networking Page 17
TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet
use to communicate with each other. To communicate over TCP, a client program and a server program
establish a connection to one another. Each program binds a socket to its end of the connection. To
communicate, the client and the server each reads from and writes to the socket bound to the connection.
What Is a Socket?
A socket is one end-point of a two-way communication link between two programs running on the network.
Socket classes are used to represent the connection between a client program and a server program. The
java.net package provides two classes--Socket and ServerSocket--that implement the client side of the
connection and the server side of the connection, respectively.
mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani