Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Creating a simple Chat Client/Server Solution in Java

Program to create a simple Chat Client/Server Solution in Java

1. Implementing a Chat Server

package com.hubberspot.examples;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

   private ServerSocket server;
   private int port = 5600;

   public Server() {
      try {
	server = new ServerSocket(port);
      } catch (IOException e) {
	   e.printStackTrace();
	}
   }

   public static void main(String[] args) {
	Server server = new Server();
	server.connection();
   }

   public void connection() {
	System.out.println("Waiting for client ...");
	try
	{
           Socket socket = server.accept();
	   System.out.println("Client accepted: " + socket);

	   DataInputStream dis = new DataInputStream(
		new BufferedInputStream(socket.getInputStream()));

	   boolean done = false;
	   while (!done)
	   {  
		try
		{  
	           String line = dis.readUTF();
		   System.out.println(line);
		   done = line.equals("bye");
		}
		catch(IOException ioe)
		{  
		   done = true;
		}
           }
	 	dis.close();				
		socket.close();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println(ioe); 
	   }

    }
}



2. Implementing a Chat Client

package com.hubberspot.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
   public static void main(String[] args) {
      try {
	//
	// Create a connection to the server socket on the server application
	//
	
        InetAddress host = InetAddress.getLocalHost();
	Socket socket = new Socket(host.getHostName(), 5600);

	//
	// Send a message to the client application
	//
	DataOutputStream dos = new DataOutputStream(
            socket.getOutputStream());
	
        DataInputStream dis = new DataInputStream(System.in);

	String line = "";
	while (!line.equals("bye"))
	{  
	   try
	   {  
		line = dis.readLine();
	        dos.writeUTF(line);
		dos.flush();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println("Sending error: " + ioe.getMessage());
				}
	   }
	   
           dis.close();
	   dos.close();
	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
   }
}



Output of the program : Client Screen

















Output of the program : Server Screen 



 
© 2021 Learn Java by Examples Template by Hubberspot