Java Chat Program
When we are developing a client/server model based application, first we need to make a decisions that whether the application is to run over TCP or over UDP.
TCP is connection-oriented and provides a reliable byte stream channel through which data flows between two end systems. UDP is connection-less and sends independent packets of data from one end system to the other, without any guarantees about delivery.
Client Side Code
import java.util.*; import java.io.*; import java.net.*; public class ClientTCP { public static void main(String[] args) throws Exception { Socket s = new Socket("localhost", 30000); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); String msg = ""; Scanner sc = new Scanner(System.in); while(true) { System.out.print("Client: "); msg = sc.nextLine(); dos.writeUTF(msg); if (msg.equals("stop")) { break; } msg = dis.readUTF(); System.out.println("Server: " + msg); } dis.close(); dos.close(); s.close(); } }
Server Side Code
import java.util.*; import java.net.*; import java.io.*; public class ServerTCP { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(30000); Socket s = ss.accept(); System.out.println("connection established..."); DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); String msg = ""; Scanner sc = new Scanner(System.in); while(true) { msg = dis.readUTF(); System.out.println("Client: " + msg); if (msg.equals("stop")) { break; } System.out.print("Server: "); msg = sc.nextLine(); dos.writeUTF(msg); } dis.close(); dos.close(); s.close(); ss.close(); } }
Output
Make sure to run the server program first and then the client program.