Java Client Server chatting program

Related searches

I got a code from the internet for a Client and Server to communicate in java. I modified it a bit, so that the server and client are able to chat to each other.

Initially my client sends a message to server, then server to client, then client to server and it goes on...(one cannot send more than one message continuously to the other). For this there is a basic code put in the while loop so that the conversation goes on 1 to 1. But as i put the while loop, the message from server is not received by client. If there is no while loop(which i have commented in the code here), then first the message is sent by client to server and then server to client and the program stops.

Please help me in making the chat go endlessly.

//SERVER
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    private static Socket socket;

    public static void main(String[] args)
    {
        try
        {
            int port = 25000;
            ServerSocket serverSocket = new ServerSocket(port);
            socket = serverSocket.accept();
            System.out.println("Server Started and listening to the port 25000");
            //while(true){
                //Server is running always. This is done using this while(true) loop
                //Reading the message from the client

                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String number = br.readLine();
                System.out.println("Received from client: "+number+"\n");

                BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
                String s = bufferRead.readLine();

                //Sending the response back to the client.
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
                bw.write(s);
                bw.flush();
                System.out.println("Sent (to " + socket + ") client: "+s+"\n");

                //String abc = bufferRead.readLine();
                //System.out.println("SAA");
            //}
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                socket.close();
            }
            catch(Exception e){}
        }
    }
}


//CLIENT
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Client {

    private static Socket socket;

    public static void main(String args[])
    {   
        try
        {
            String host = "localhost";
            int port = 25000;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);

            //while(true){
                //Send the message to the server
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);

                BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
                String s = bufferRead.readLine();

                String sendMessage = s + "\n";
                bw.write(sendMessage);
                bw.flush();
                System.out.println("Sent to server: " +sendMessage+"\n");

                //Get the return message from the server
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                System.out.println(socket);
                String message = br.readLine();
                System.out.println("Received from server: "+message+"\n");
            //}
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
            //Closing the socket
            try
            {
                socket.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
Server.java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

public class Server implements Runnable {

ServerSocket serversocket;
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in="",out="";

public Server() {
    try {
        t1 = new Thread(this);
        t2 = new Thread(this);
        serversocket = new ServerSocket(5000);
        System.out.println("Server is waiting. . . . ");
        socket = serversocket.accept();
        System.out.println("Client connected with Ip " +        socket.getInetAddress().getHostAddress());
        t1.start();;
        t2.start();

    } catch (Exception e) {
    }
 }

 public void run() {
    try {
        if (Thread.currentThread() == t1) {
            do {
                br1 = new BufferedReader(new InputStreamReader(System.in));
                pr1 = new PrintWriter(socket.getOutputStream(), true);
                in = br1.readLine();
                pr1.println(in);
            } while (!in.equals("END"));
        } else {
            do {
                br2 = new BufferedReader(new   InputStreamReader(socket.getInputStream()));
                out = br2.readLine();
                System.out.println("Client says : : : " + out);
            } while (!out.equals("END"));
        }
    } catch (Exception e) {
    }
}

public static void main(String[] args) {
    new Server();
}
}

Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

public class Client implements Runnable {

BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in = "", out = "";

public Client() {
    try {
        t1 = new Thread(this);
        t2 = new Thread(this);
        socket = new Socket("localhost", 5000);
        t1.start();;
        t2.start();

    } catch (Exception e) {
    }
}

public void run() {

    try {
        if (Thread.currentThread() == t2) {
            do {
                br1 = new BufferedReader(new InputStreamReader(System.in));
                pr1 = new PrintWriter(socket.getOutputStream(), true);
                in = br1.readLine();
                pr1.println(in);
            } while (!in.equals("END"));
        } else {
            do {
                br2 = new BufferedReader(new   InputStreamReader(socket.getInputStream()));
                out = br2.readLine();
                System.out.println("Server says : : : " + out);
            } while (!out.equals("END"));
        }
    } catch (Exception e) {
    }

 }

 public static void main(String[] args) {
     new Client();
 }
 }

Creating a simple Chat Client/Server Solution, The client is implemented as an Applet, but a Frame would have worked just as well (for a stand-alone program). Step 1: Simple, one-time Server import java.net. *;� i am creating server client chatting program through console.When i run the program , it just take inputs and inputs infinitely. Server code import java.net.*; import java.io.*; public class Server

    //server.java
import java.io.*;
import java.net.*;
public class server {
   public static void main(String []V){
	   try{
		   ServerSocket ss = new ServerSocket(1201);
		   Socket s = ss.accept();
		   
		   DataInputStream Din = new DataInputStream(s.getInputStream());
		   DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
		   
		   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		   
		   String MsgIn="",MsgOut="";
		   
		   while(!MsgIn.equals("end")){
			   MsgIn = Din.readUTF();
			   System.out.println(MsgIn);
			   MsgOut = br.readLine();
			   Dout.writeUTF(MsgOut);
			   Dout.flush();
		   }
		   s.close();	   
	   }catch(Exception e){
	   
	   }
   
}
}
//clients.java
import java.io.*;

import java.net.*;

import javax.xml.crypto.Data;
public class clients {
     public static void main(String []S){
    	 try{
    		 Socket s = new Socket("192.168.0.103",1201);//my pc's ip
    		 //Socket s = new Socket("192.168.0.100",1201);
    		 DataInputStream Din = new DataInputStream(s.getInputStream());
    		 DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
    		 
    		 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    		 String MsgIn="",MsgOut="";
    		 
    		 while(!MsgIn.equals("end")){
    			 MsgOut = br.readLine();
    			 Dout.writeUTF(MsgOut);
    			 MsgIn = Din.readUTF();
    			 System.out.println(MsgIn);
    		 }
    	 }catch(Exception e){
    		 
    	 }
     }
     
}

Java Client Server chatting program, Server.java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.*; public class Server implements� The ChatClient starts the client program, connects to a server specified by hostname/IP address and port number. Once the connection is made, it creates and starts two threads ReadThread and WriteThread. Here is source code of the ChatClient class: package net.codejava.networking.chat.client; import java.net.*; import java.io.*;

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

class serversvi1
{
    public static void main(String svi[])throws IOException
    {
        try
        {
            ServerSocket servsock=new ServerSocket(5510);
            DataInputStream dis=new DataInputStream(System.in);
            System.out.println("enter the file name");
            String fil=dis.readLine();
            System.out.println(fil+" :is file transfer");
            File myfile=new File(fil);

            while(true)
            {
                Socket sock=servsock.accept();
                byte[] mybytearray=new byte[(int)myfile.length()];
                BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
                bis.read(mybytearray,0,mybytearray.length);
                OutputStream os=sock.getOutputStream();
                os.write(mybytearray,0,mybytearray.length);
                os.flush();
                sock.close();

            }
        }

        catch(Exception saranvi)
        {
            System.out.print(saranvi);
        }
    }
}

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

class clientsvi1
{
    public static void main(String svi[])throws IOException
    {
        try
        {
            Socket sock=new Socket("localhost",5510);
            byte[] bytearray=new byte[1024];
            InputStream is=sock.getInputStream();
            DataInputStream dis=new DataInputStream(System.in);
            System.out.println("enter the file name");
            String fil=dis.readLine();
            FileOutputStream fos=new FileOutputStream(fil);
            BufferedOutputStream bos=new BufferedOutputStream(fos);
            int bytesread=is.read(bytearray,0,bytearray.length);
            bos.write(bytearray,0,bytesread);
            System.out.println("out.txt file is received");
            bos.close();
            sock.close();
        }

        catch(Exception SVI)
        {
            System.out.print(SVI);
        }
    }
}

How to Create a Chat Console Application in Java using Socket, The Java Chat application you are going to build is a console application that is launched from the command line. The server and clients can� Multiple Client Server Chat Program In Java A typical Java program runs in a single process, and is not interested in multiple processes. Code for Version 2- Client as a Web Browser (Telnet Applet) B. RPA Enterprise Platform from Automation Anywhere the Global Enterprise RPA solution.

Server Client Chat Application with Java Socket Programming, The following is the source code, explanation and results of the execution of this application. server.java. On the server, first opening port 9999� The client or server might close the connection whenever they want. The aim of this project is to develop a Chat application using client server architecture which relies on Socket programming provided by java. The client is implemented using two threads - one thread to interact with the server and the other with the.

Invoke the start () method. ClientHandler class : Similar to previous article, we create a helper class for handling various requests. This time, along with the socket and streams, we introduce a name variable. This will hold the name of the client that is connected to the server.

Creating a simple Chat Client/Server Solution. Here is an example of how to extend a very simple client-server demo program into a fully functioning (but simple) Chat Client/Server package. There are five stages involved:

Comments
  • Write code for getting input and output stream outside while loop.
  • It doesn't affect. By using while loop, client doesn't get any message.
  • Can u explain what you did...or rather what i did wrong?
  • I believe this one is multi-threaded so that the server and client and both send and recieve messages at the same time
  • Please edit your answer to describe how this answers the question, and explain what the code does. Code only answers are discouraged.
  • Welcome to SO! Please format your answer so we can read it. Edit your answer and click the help link to see how.
  • Also, to make for a great answer, it helps to add textual commentary/descriptions of your provided solution, to help the OP (and future readers!) understand your answer.