AJP Programs (16.... )

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Chat Application using Server Socket and Socket Class

Server.java

import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Connection established");
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str, str1;
while ((str = br.readLine()) != null) {
System.out.println(str);
str1 = kb.readLine();
ps.println(str1);
}
ps.close(); br.close();
kb.close(); ss.close();
s.close(); System.exit(0);
} // end of while
}
}
Client.java

import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) throws Exception
{
Socket s = new Socket("localhost", 888);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
String str, str1;
while (!(str = kb.readLine()).equals("exit"))
{
dos.writeBytes(str + "\n");
str1 = br.readLine();
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}
ServerSide

ClientSide
Program to demonstrate the use of DatagramPacket and DatagramSocket

DSender.java

import java.net.*;
import java.util.*;
public class DSender {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
DatagramSocket ds = new DatagramSocket();
System.out.println("Send Massage...!");
String str = sc.nextLine();
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
ds.send(dp); ds.close();
}
}

DReceiver.java

import java.net.*;
public class DReceiver {
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
DSender

DReceiver

You might also like