Vous êtes sur la page 1sur 25

author sid

1. The message entered in the client is sent to the server and the server encodes
the message and returns it to the client. Encoding is done by replacing a
character by the character next to it i.e. a as b, b as c z as a. This process is
done using the TCP/IP protocol. Write a Java program for the above.
SERVER:
import java.io.*;
import java.net.*;
class server {
public static void main(String argv[]) throws Exception
{
String no1;
ServerSocket welcomeSocket = new ServerSocket(6788);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
no1 = inFromClient.readLine();
int n=no1.length();
int i;

String zz="";
char d;
char c[]=no1.toCharArray();
for(i=0;i<n;i++)
{
if(c[i]=='z')
d='a';
else
{int num=(int)c[i];
num++;
d=(char)num;
}zz=zz+d;
}
outToClient.writeBytes(zz+'\n');
}}}
CLIENT:

import java.io.*;
import java.net.*;
class client{
public static void main(String argv[]) throws Exception
{
String no1;
String mod;
BufferedReader inFromUser =

new BufferedReader(new InputStreamReader(System.in));


Socket clientSocket = new Socket("localhost", 6788);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter MESSAGE to be encoded\n");
no1=inFromUser.readLine();
outToServer.writeBytes(no1 + '\n');
mod = inFromServer.readLine();
System.out.println("FROM SERVER:encoded " + mod);
clientSocket.close();
}
}
OUTPUT:

2. Write a Java program to develop a simple Chat application.


SERVER:
import java.net.*;
import java.io.*;
class chatserver{
public static void main(String[ ] args){
try{
ServerSocket welcomeSocket = new ServerSocket(8989);
Socket connectionSocket = welcomeSocket.accept();
String user,srv;
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
do{
user=inFromClient.readLine();
System.out.println("Client: "+user);
srv=inFromServer.readLine();
outToClient.writeBytes(srv+'\n');
}while(srv!=""||srv!="\n");
connectionSocket.close();
welcomeSocket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
CLIENT:
import java.io.*;
import java.net.*;
class chatclient{
public static void main(String[ ] args){
try{
Socket clientSocket = new Socket("localhost",8989);
String us,sr;
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
do{
us=inFromUser.readLine();
outToServer.writeBytes(us+'\n');
sr=inFromServer.readLine();
System.out.println("Ser: "+sr+'\n');
}while(us!=""||us!="\n");
clientSocket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
OUTPUT:

3. Illustrate with the help of Socket programming that how a Server can Run in
Infinite Loop handling Multiple Client Requests, one at a time

SERVER:
import java.io.*;
import java.net.*;

class server2 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String cap;

ServerSocket welcomeSocket = new ServerSocket(6789);


while(true) {
Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

no1 = inFromClient.readLine();
no2 = inFromClient.readLine();

int m=Integer.parseInt(no1);
int b=Integer.parseInt(no2);

int sum=m+b;
int sub=m-b;
int mul=m*b;
int div=m/b;

String z=String.valueOf(sum);
String x=String.valueOf(sub);
String c=String.valueOf(mul);
String v=String.valueOf(div);
cap = z+' '+x+' '+c+' ' +v+ '\n';

outToClient.writeBytes(cap);
}
}
}
CLIENT 1:
import java.io.*;
import java.net.*;
class client1 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String mod;

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter 2 numbers\n");
no1=inFromUser.readLine();

no2=inFromUser.readLine();
outToServer.writeBytes(no1 + '\n');
outToServer.writeBytes(no2 + '\n');

mod = inFromServer.readLine();

System.out.println("FROM SERVER: " + mod);

clientSocket.close();
}
}

CLIENT 2:
import java.io.*;
import java.net.*;
class client2 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String mod;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter 2 numbers\n");
no1=inFromUser.readLine();

no2=inFromUser.readLine();
outToServer.writeBytes(no1 + '\n');
outToServer.writeBytes(no2 + '\n');

mod = inFromServer.readLine();

System.out.println("FROM SERVER: " + mod);

clientSocket.close();
}
}

OUTPUT:
iteBytes(us+'\n');
sr=inFromServer.readLine();
System.out.println("Ser: "+sr+'\n');
}while(us!=""||us!="\n");
clientSocket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
OUTPUT:

3. Illustrate with the help of Socket programming that how a Server can Run in
Infinite Loop handling Multiple Client Requests, one at a time

SERVER:
import java.io.*;
import java.net.*;

class server2 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String cap;

ServerSocket welcomeSocket = new ServerSocket(6789);


while(true) {
Socket connectionSocket = welcomeSocket.accept();

BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

no1 = inFromClient.readLine();
no2 = inFromClient.readLine();

int m=Integer.parseInt(no1);
int b=Integer.parseInt(no2);

int sum=m+b;
int sub=m-b;
int mul=m*b;
int div=m/b;

String z=String.valueOf(sum);
String x=String.valueOf(sub);
String c=String.valueOf(mul);
String v=String.valueOf(div);

cap = z+' '+x+' '+c+' ' +v+ '\n';

outToClient.writeBytes(cap);
}
}
}
CLIENT 1:
import java.io.*;
import java.net.*;
class client1 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String mod;

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter 2 numbers\n");
no1=inFromUser.readLine();
no2=inFromUser.readLine();
outToServer.writeBytes(no1 + '\n');
outToServer.writeBytes(no2 + '\n');

mod = inFromServer.readLine();

System.out.println("FROM SERVER: " + mod);

clientSocket.close();
}
}

CLIENT 2:
import java.io.*;
import java.net.*;
class client2 {

public static void main(String argv[]) throws Exception


{
String no1;
String no2;
String mod;

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
System.out.println("Enter 2 numbers\n");
no1=inFromUser.readLine();

no2=inFromUser.readLine();
outToServer.writeBytes(no1 + '\n');
outToServer.writeBytes(no2 + '\n');

mod = inFromServer.readLine();

System.out.println("FROM SERVER: " + mod);

clientSocket.close();
}
}
******************
CYCLESHEET3
14bit0173
Akshat Pradhan

Prof. Sudha.s
Network Programming lab
L31 L32
11-02-2017

1. Create a concurrent server that provides the service to monitor spammers,


and inform
clients whether a host attempting to connect to them is a known spammer or not.
Use the service name as sbl.spamhaus.org

CODE
Server
import java.util.*;
import java.net.*;
import java.io.*;

public class server extends Thread{


String spchk;
server(String x){
this.spchk=x+"sbl.spamhaus.org.(127.0.0.2)";
System.out.println(spchk);
}
public void run(){
try{
InetAddress check = InetAddress.getByName(spchk);
System.out.println("Spammer");

}catch(Exception e){
System.out.println("Not a spam");
}

public static void main(String[] args){

ServerSocket server;
Socket connection;
ObjectInputStream input;
try{
server = new ServerSocket(6789,100);
connection = server.accept();
input = new
ObjectInputStream(connection.getInputStream());
String cstring =(String) input.readObject();
InetAddress clientip = InetAddress.getByName(cstring);
byte[] spamchk=clientip.getAddress();
String revip="";
for(int i=spamchk.length;i>0;i--){
if((int) spamchk[i-1]<0){
int n = spamchk[i-1]+256;
revip=revip+n;
revip=revip+".";
System.out.println(revip);
}
else{
revip=revip+spamchk[i-1];
revip=revip+".";
System.out.println(revip);
}
}
server x = new server(revip);
x.start();
x.join();
server.close();
connection.close();
input.close();

}catch(Exception e){
e.printStackTrace();
}

Client

import java.io.*;
import java.net.*;
import java.util.*;
public class client {

public static void main(String[] args){


Socket connection;
ObjectOutputStream output;

try{
connection = new Socket("127.0.0.1", 6789);
output = new
ObjectOutputStream(connection.getOutputStream());
output.writeObject("207.87.34.17");
output.flush();
output.close();
connection.close();
}catch(Exception e){
e.printStackTrace();
}
}

Output

a.
Web server logs track the hosts that access a website. By default, the log reports
the
IP addresses of the sites that connect to the server. However, you can often get
more
information from the names of those sites than from their IP addresses. Most web
servers have an option to store hostnames instead of IP addresses, but this can
hurt
performance because the server needs to make a DNS request for each hit. It is
much
more efficient to log the IP addresses and convert them to hostnames at a later
time.
Create a file named logfile with some details of 10 clients with the following
data for
each client.
A typical line in the common logfile format looks like this:
site logName fullName [date:time GMToffset] "req file proto" status length
205.160.186.76 unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
Write a program called Weblog that reads a web server logfile and prints each line
with IP addresses converted to hostnames.
filelog.txt
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
site logName fullName [date:time GMToffset] "req file proto" status length
<205.160.186.76> unknown - [17/Jun/2013:22:53:58 -0500] "GET /bgs/greenbg.gif HTTP
1.0" 200 50
Code
import java.io.*;
import java.net.*;
importjava.util.*;
publicclass client {

publicstaticvoid main(String[] args){


try{

FileInputStream in = new FileInputStream("filelog.txt");


charc;

while((c=(char)in.read())!='\0'){
if(c=='<'){
chare;
String address="";
while((e =(char)in.read())!='>'){
address=address+e;
}
InetAddress add =
InetAddress.getByName(address);
System.out.println("IP address:
"+add.getHostAddress()+"Host name: "+add.getHostName());
}

}catch(Exception e){
e.printStackTrace();
}
}

}
Output

Rewrite the program by using Muiltithread concept, such that One main thread
can read the logfile and pass off individual entries to other threads for
processing
Code
importjava.util.*;
import java.net.*;
import java.io.*;

public class server extends Thread{


String adder;
server(String x){
this.adder=x;
}
publicvoid run(){
try{

InetAddress add = InetAddress.getByName(adder);


System.out.println("IP address:
"+add.getHostAddress()+"Host name: "+add.getHostName());

}catch(Exception e){
e.printStackTrace();
}

publicstaticvoid main(String[] args){

try{
FileInputStream in = new FileInputStream("filelog.txt");
charc;

while((c=(char)in.read())!='\0'){
if(c=='<'){
chare;
String address="";
while((e =(char)in.read())!='>'){
address=address+e;
}
server a = new server(address);
a.start();
a.join();
}

}
}catch(Exception e){
e.printStackTrace();
}
}

Output

Write a program that displays the details of all the network interfaces of a host
Code

Import java.io.*;
import java.net.*;
import java.util.*;
publicclass client {

publicstaticvoid main(String[] args){

try{
Enumeration<NetworkInterface>interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
System.out.println(ni);
}
}catch(Exception e){
e.printStackTrace();
}

}
}
Output

Write a test code that would check whether the server socket on port 4444 was
accessible
via all interfaces.
Code
importjava.io.*;
import java.net.*;
import java.util.*;
publicclass client {

publicstaticvoid main(String[] args){

try{
ServerSocket server = new ServerSocket(4444);
Enumeration<NetworkInterface>interfaces =
NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress>adder = ni.getInetAddresses();
Socket checker;
InetAddress ninet;
while(adder.hasMoreElements()){
ninet = adder.nextElement();
try{

checker = new Socket(ninet,4444);


System.out.println(ni.getDisplayName()+"
connected to "+ ninet);
}catch(Exception e){
System.out.println(ni.getDisplayName()+"
unnable to connect "+ ninet);
}
}

}
}catch(Exception e){
e.printStackTrace();
}

}
}

SUBA SHANTINI

1. import java.io.*;
import java.net.*;
import java.util.*;
class URLConnect
{
public static void main(String [] args)throws MalformedURLException
{
try {

URL u = new URL("http://www.vit.ac.in");

URLConnection uc = u.openConnection();

InputStream buffer = new BufferedInputStream(uc.getInputStream());

Reader r = new InputStreamReader(buffer);

int c;

while ((c = r.read()) != -1)


{
System.out.print((char) c);
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}

2.import java.io.*;
import java.net.*;
import java.util.*;
class SpecificHeader
{
public static void main(String [] args)throws MalformedURLException
{
try {
URL u = new URL("http://www.vit.ac.in");

URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
String contentEncoding = uc.getContentEncoding();
Date documentSent = new Date(uc.getDate());
Date documentLastModified= new Date(uc.getLastModified());
Date documentExpired= new Date(uc.getExpiration());
System.out.println("Content Type :"+contentType+"\nContent Length
:"+contentLength+"\nContent Encoding :"+contentEncoding+
"\nDate Document Sent :"+documentSent+"\nLast Modified
"+documentLastModified+"\nExpiry Date :"+documentExpired);
}
catch (IOException e)
{
System.out.println(e);
}
}
}

b.
import java.io.*;
import java.net.*;
import java.util.*;
class ArbitraryHeader
{
public static void main(String [] args)throws MalformedURLException
{
try {

URL u = new URL("http://www.vit.ac.in");

URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
String contentType1 = uc.getHeaderField("content-type");
String header = uc.getHeaderFieldKey(5);
Date now = new Date(uc.getHeaderFieldDate("date", 0));
Date now1 = new Date(uc.getHeaderFieldInt("date", -1));
System.out.println("Header Field: "+ contentType1+"\nHeader Field Key:
"+header+"\nHeader Field Date: "+now+"\nHeader Field Int: "+now1);

}
catch (IOException e)
{
System.out.println(e);
}
}
}

3.
import java.io.*;
import java.net.*;
import java.util.*;
class HTTPHeader
{
public static void main(String [] args)throws MalformedURLException
{
try {
URL u = new URL("http://www.vit.ac.in");
URLConnection uc = u.openConnection();
try{
uc.setRequestProperty("Cookie","session=100678945");
System.out.println("Request Property: "+uc.getRequestProperty("Cookie"));
}
catch (IllegalArgumentException e)
{
System.out.println(e);
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}

Server CODE:
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

public class DictServer {


public static void main(String[] args) throws Exception {
try{
ServerSocket ss =new ServerSocket(8999);
Socket s = ss.accept();
System.out.println("Successfully connected to client");

DataInputStream dis = new DataInputStream(s.getInputStream());


DataOutputStream dos = new DataOutputStream(s.getOutputStream());

while(true) {
String send = "", receive = "";
//receive = dis.readUTF();

if((receive = dis.readUTF()) != null) {


if(receive == "quit"||receive == "Quit"||receive == "QUIT")
break;
else {
System.out.println("Query received: "+receive);
StringTokenizer st = new StringTokenizer(receive);
//while(st.hasMoreTokens()) {
String define = st.nextToken();
String file = st.nextToken().concat(".txt");
//System.out.println(file);
String word = st.nextToken();
try {
File f = new File(file);

FileInputStream fis = new FileInputStream(f);


BufferedReader br = new BufferedReader(new
InputStreamReader(fis));
for(String line = br.readLine(); line != null;
line = br.readLine()) {
//System.out.println(line);
StringTokenizer str = new
StringTokenizer(line);
if(str.nextToken().equals(word)) {
send = new String(line);
break;
}
line = "";
}
//fis.flush();
} catch(Exception ex) {
System.out.println(ex);
}
//}
dos.writeUTF(send);
}
}
}
} catch(Exception e){
System.out.println(e);
}
}
}

Client CODE:
import java.io.*;
import java.net.*;

public class DictClient {


public static void main(String[] args) throws Exception {
Socket s = new Socket();
try {
SocketAddress address = new InetSocketAddress("127.0.01", 8999);
s.connect(address);
System.out.println("Successfully connected to server");

while(true) {
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

String dict, word, send, receive;


System.out.println("Enter the dictionary:");
dict = br.readLine();
if(dict.equals("quit")){
dos.writeUTF("quit");
break;
}
System.out.println("Enter the word:");
word = br.readLine();
send = "DEFINE eng-"+dict+" "+word;
System.out.println("Query sent: "+send);
dos.writeUTF(send);
if((receive = dis.readUTF()) != null)
System.out.println(receive);
else
System.out.println("Word not found.");
}

} catch(Exception e) {
System.out.println("This is catch block");
System.err.println(e);
} finally {
try{
s.close();
} catch(Exception e) {
}
}
}
}
SSL SOCKET

SLServer :
import java.io.*;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.*;

public class ServerSSL {


public static void main(String[] args) throws Exception {
SSLServerSocket server;
try {
SSLServerSocketFactory factory = (SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
server = (SSLServerSocket) factory.createServerSocket(8999);
SSLSocket client = (SSLSocket) server.accept();
System.out.println("Securely connected to client...");

DataInputStream dis = new DataInputStream(client.getInputStream());


DataOutputStream dos = new DataOutputStream(client.getOutputStream());

/*String[] cipher = server.getEnabledCipherSuites();


/*int len = cipher.length;
dos.writeUTF(String.valueOf(len));*/

String[] supported = client.getSupportedCipherSuites();


//dos.writeUTF(cipher[5]);
client.setEnabledCipherSuites(supported);

String receive = "";


if((receive = dis.readUTF()) != null)
System.out.println("Received: "+receive);

dos.writeUTF(receive);

server.close();
} catch(Exception ex) {
System.err.println(ex);
}
}
}
SSLClient :
import javax.net.ssl.*;
import java.io.*;

public class ClientSSL {


public static void main(String[] args) throws Exception {
try {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket client = (SSLSocket) factory.createSocket("127.0.0.1", 8999);
System.out.println("Securely connected to server...");

DataInputStream dis = new DataInputStream(client.getInputStream());


DataOutputStream dos = new DataOutputStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

/*String length = dis.readUTF();


int l = Integer.parseInt(length);
String[] s = new String[l];
for(int i = 0; i < l; i++)
s[i] = dis.readUTF();*/

String[] supported = client.getSupportedCipherSuites();


client.setEnabledCipherSuites(supported);
/*String cipher = dis.readUTF();
String[] selCipher = {"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"};
client.setEnabledCipherSuites(selCipher);*/

String send, receive = "";


send = br.readLine();
dos.writeUTF(send);
System.out.println("Sent : "+send);

if((receive = dis.readUTF()) != null)


System.out.println("Received : "+receive);
} catch(Exception ex) {
System.err.println(ex);
}
}
}

MultiSend :
import java.net.*;
import java.io.*;

public class MultiSend {


public static void main(String[] args) {
try {
String s = "Really important message";
byte[] data = s.getBytes();
DatagramPacket dp = new DatagramPacket(data, data.length);
dp.setPort(2000);
DatagramSocket socket = new DatagramSocket();
String network = "128.238.5.";
for(int host = 1; host < 255; host++) {
try {
InetAddress remote = InetAddress.getByName(network + host);
dp.setAddress(remote);
socket.send(dp);
//System.out.println("Sent to address : "+ network + host);
} catch(Exception e) {
//skip it, continue with next host
}
}
} catch(Exception ex) {
System.err.println(ex);
}
}
}

SINGLE DOC

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

class Ucli {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}

---
import java.io.*;
import java.net.*;
import java.util.*;

class User {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[5];
byte[] sendData = new byte[5];
while(true)
{

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());

char c[]=sentence.toCharArray();
int n=c.length;
int i;
char zu;
String str="";

for(i=0;i<n;i++)
{
if(c[i]=='z')
{
zu='a';
}
else{
int num=(int)c[i];
num++;
zu=(char)num;
}
str=str+zu;

sendData = str.getBytes();

InetAddress IPAddress = receivePacket.getAddress();


int port = receivePacket.getPort();

DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
-----------------------------------------------
import java.io.*;

import java.net.*;

class UDPClient {

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

BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));

DatagramSocket clientSocket = new DatagramSocket();//for client socket we don't


need port no ..to create server socket we need port no.

InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData = new byte[1024];

String sentence = inFromUser.readLine();

sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
IPAddress, 9876);

clientSocket.send(sendPacket);

-------
import java.io.*;

import java.net.*;

class UDPServer {

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

DatagramSocket serverSocket = new DatagramSocket(9876);//create socket wd only


port no

int i;

char c,cc;

byte[] receiveData = new byte[1024];//data to be sent back

while(true){

DatagramPacket receivePacket = new DatagramPacket(receiveData,


receiveData.length);//datagram packet created to receive data

serverSocket.receive(receivePacket);//we receive the packet from client in the dp


object

String sentence = new String(receivePacket.getData());//we extract the data out of


the packet and convert to string

System.out.println("RECEIVED: " + sentence);//print the recieved data as string

System.out.println("This packet is addressed to "+ receivePacket.getAddress() + "


on port " + receivePacket.getPort());

System.out.println("There are " + receivePacket.getLength()

+ " bytes of data in the packet");

System.out.println(new String(receivePacket.getData(), "UTF-8"));

System.out.println(receivePacket.getOffset());

System.out.println(receivePacket.getLength());

System.out.println(receivePacket.getSocketAddress());

}
EXTRA
import java.io.*;
import java.util.*;
import java.util.concurrent.*;

// Requires Java 7 for try-with-resources and multi-catch


//Pooled Weblog
public class PooledWeblog {

private final static int NUM_THREADS = 4;

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


ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
Queue<LogEntry> results = new LinkedList<LogEntry>();

try (BufferedReader in = new BufferedReader(


new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));) {
for (String entry = in.readLine(); entry != null; entry = in.readLine()) {
LookupTask task = new LookupTask(entry);
Future<String> future = executor.submit(task);
LogEntry result = new LogEntry(entry, future);
results.add(result);
}
}

// Start printing the results. This blocks each time a result isn't ready.
for (LogEntry result : results) {
try {
System.out.println(result.future.get());
} catch (InterruptedException | ExecutionException ex) {
System.out.println(result.original);
}
}

executor.shutdown();
}

private static class LogEntry {


String original;
Future<String> future;

LogEntry(String original, Future<String> future) {


this.original = original;
this.future = future;
}
}
}

//downloading a web page


import java.io.*;
import java.net.*;
public class SourceViewer {
public static void main (String[] args) {
if (args.length > 0)
{ InputStream in = null;
try { // Open the URL for reading
URL u = new URL(args[0]);
in = u.openStream();
// buffer the input to increase performance
in = new BufferedInputStream(in);
// chain the InputStream to a Reader
Reader r = new InputStreamReader(in);
int c;
while ((c = r.read()) != -1)
{
System.out.print((char) c);
}
} catch (MalformedURLException ex)
{ System.err.println(args[0] + " is not a parseable URL");
} catch (IOException ex)
{ System.err.println(ex);
}
finally
{ if (in != null)
{
try {
in.close();
} catch (IOException e)
{ // ignore
}
}
} }

// gui authenticator
import javax.mail.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MailAuthenticator extends Authenticator {

private JDialog passwordDialog = new JDialog(new JFrame(), true);


private JTextField usernameField = new JTextField(20);
private JPasswordField passwordField = new JPasswordField(20);
private JButton okButton = new JButton("OK");

public MailAuthenticator() {
this("");
}

public MailAuthenticator(String username) {


JLabel mainLabel = new JLabel(
"Please enter your username and password: ");
JLabel userLabel = new JLabel("Username: ");
JLabel passwordLabel = new JLabel("Password: ");

Container pane = passwordDialog.getContentPane();


pane.setLayout(new GridLayout(4, 1));
pane.add(mainLabel);
JPanel p2 = new JPanel();
p2.add(userLabel);
p2.add(usernameField);
usernameField.setText(username);
pane.add(p2);
JPanel p3 = new JPanel();
p3.add(passwordLabel);
p3.add(passwordField);
pane.add(p3);
JPanel p4 = new JPanel();
p4.add(okButton);
pane.add(p4);
passwordDialog.pack();

ActionListener listener = new HideDialog();


okButton.addActionListener(listener);
usernameField.addActionListener(listener);
passwordField.addActionListener(listener);
}

class HideDialog implements ActionListener {


@Override
public void actionPerformed(ActionEvent event) {
passwordDialog.setVisible(false);
}
}

public PasswordAuthentication getPasswordAuthentication() {


passwordDialog.setVisible(true);

// getPassword() returns an array of chars for security reasons.


// We need to convert that to a String for
// the PasswordAuthentication() constructor.
String password = new String(passwordField.getPassword());
String username = usernameField.getText();
// Erase the password in case this is used again.
// The provider should cache the password if necessary.
passwordField.setText("");
return new PasswordAuthentication(username, password);
}
}

//url parts
import java.net.*;

public class GetURLParts {

public static void main(String args[]) {

try {
URL u = new URL("http://www.java2s.com");
System.out.println("The URL is " + u);
System.out.println("The protocol part is " + u.getProtocol());
System.out.println("The host part is " + u.getHost());
System.out.println("The port part is " + u.getPort());
System.out.println("The file part is " + u.getFile());
System.out.println("The ref part is " + u.getRef());
} // end try
catch (MalformedURLException e) {
System.err.println("not a URL I understand.");
}

} // end main

//ip characteristics
import java.net.*;

public class IPCharacteristics {

public static void main(String[] args) {

try {
InetAddress address = InetAddress.getByName(args[0]);

if (address.isAnyLocalAddress()) {
System.out.println(address + " is a wildcard address.");
}
if (address.isLoopbackAddress()) {
System.out.println(address + " is loopback address.");
}

if (address.isLinkLocalAddress()) {
System.out.println(address + " is a link-local address.");
} else if (address.isSiteLocalAddress()) {
System.out.println(address + " is a site-local address.");
} else {
System.out.println(address + " is a global address.");
}

if (address.isMulticastAddress()) {
if (address.isMCGlobal()) {
System.out.println(address + " is a global multicast address.");
} else if (address.isMCOrgLocal()) {
System.out.println(address
+ " is an organization wide multicast address.");
} else if (address.isMCSiteLocal()) {
System.out.println(address + " is a site wide multicast
address.");
} else if (address.isMCLinkLocal()) {
System.out.println(address + " is a subnet wide multicast
address.");
} else if (address.isMCNodeLocal()) {
System.out.println(address
+ " is an interface-local multicast address.");
} else {
System.out.println(address + " is an unknown multicast
address type.");
}
} else {
System.out.println(address + " is a unicast address.");
}
} catch (UnknownHostException ex) {
System.err.println("Could not resolve " + args[0]);
}
}
}