Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Muliple Client Server chat application..how to send message from server..

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation Muliple Client Server chat application..how to send message from server..

    hi i am new to java I wrote following code..all clients to server communicating well..when i want to send message from Server to connected clients client dont receive it..how to resolve this.code displayed below
    Server:
    import java.io.*;
    import java.net.*;
    class MulServerThread
    {
    //declaration
    private static ServerSocket serverSocket = null;
    private static Socket socket = null;
    private static final int maxclients = 5;
    //array of thread creation
    private static final clientThread[] threads = new clientThread[maxclients];//accepts only 5 clients

    public static void main(String args[])
    {
    try
    {
    //start of main method
    int port = 1774;
    serverSocket = new ServerSocket(port);
    System.out.println("waiting for client......");
    while(true)
    {
    socket = serverSocket.accept();//accept the
    int i = 0;
    //pass into new client thread
    for(i = 0;i < maxclients;i++)
    {
    if(threads[i]==null)
    {
    (threads[i] = new clientThread(socket,threads)).start();//start array of thread
    break;
    }
    }
    if(i == maxclients)
    {
    PrintStream out = new PrintStream(socket.getOutputStream());//send data to the client
    out.println("Server busy........please try after some time.");
    //close the connection
    out.close();
    socket.close();
    }
    }
    }
    catch(IOException e)
    {
    System.out.println("IOException"+e);
    }
    }
    }
    class clientThread extends Thread
    {
    private int maxclients;
    private DataInputStream is = null;//receive response from client
    private PrintStream out = null;//send the data to client
    private Socket socket = null;
    private final clientThread[] threads;
    public clientThread(Socket socket,clientThread[] threads)
    {
    this.socket = socket;
    this.threads = threads;
    maxclients = threads.length;
    }
    public void run()
    {
    //start of run method
    int maxclients = this.maxclients;
    clientThread[] threads = this.threads;
    try
    {
    //create input output stream for client
    is=new DataInputStream(socket.getInputStream());
    //send data to the client
    out = new PrintStream(socket.getOutputStream());
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String send;

    out.println("Hai...Enter your name.");
    String name,message;
    name = is.readLine();
    out.println("Hello "+name+" to our chat room.\tTo leave enter close");//display the message to available client thread
    for(int i = 0;i < maxclients;i++)
    {
    if(threads[i] != null)
    {
    threads[i].out.println("New user "+name+" entered in to the chat room");
    }
    }
    System.out.println("New user "+name+" entered in to the chat room\n");//print in a console
    /*for(int i=0;i<maxclients;i++)
    {
    if(threads[i]!=null)
    {
    send=br.readLine();
    threads[i].out.println("Server:"+send);
    }
    }*/
    while(true)
    {
    message = is.readLine();
    //message equals to close..terminate the connection
    if(message.equals("close"))
    {
    break;
    }
    for(int i = 0;i < maxclients;i++)
    {
    if(threads[i] != null)
    {
    threads[i].out.println(name + ">" +message);
    }
    }


    System.out.println(name + ">" +message+"\n");//console
    }
    for(int i = 0;i < maxclients;i++)
    {
    if(threads[i] != null)
    {
    threads[i].out.println("The user " + name+ " left the chat ");
    }
    }
    System.out.println("The user " + name + " left the chat\n");
    out.println("Bye "+name);
    System.out.println("Bye "+name+"\n");
    for(int i = 0;i < maxclients;i++)
    {
    if(threads[i] == this)
    {
    threads[i] = null;//current thread variable null so new client thread accepted by the server
    }
    }
    //close connection
    is.close();
    out.close();
    }
    catch(IOException e)
    {
    System.out.println(e);
    }
    }//enf of run method
    }
    Client:
    import java.io.*;
    import java.net.*;
    public class MulClientThread implements Runnable
    {
    //declaration
    static int port = 1774;
    static String host = "192.168.1.113";
    static Socket soc = null;
    static BufferedReader input = null;
    static DataInputStream is = null;//receive response from server
    static boolean end = false;
    static PrintStream ps = null;//send data to server
    public static void main(String args[])throws IOException
    {
    //start of main method
    soc = new Socket(host,port);//socket creation for communication
    System.out.println("chat started using multi thread on port "+port+"\n on host "+host);
    //input and output stream communication with server
    input = new BufferedReader(new InputStreamReader(System.in));
    ps = new PrintStream(soc.getOutputStream());
    is = new DataInputStream(soc.getInputStream());
    String receive;
    BufferedReader in=new BufferedReader(new InputStreamReader(soc.getInputStream()));

    //write the data to socket
    if(soc != null&&ps != null&&is != null)
    {
    try
    {
    //Create a thread to read from the server
    new Thread(new MulClientThread()).start();
    while(!end)
    {
    ps.println(input.readLine());
    }


    }
    catch(IOException ex)
    {
    System.out.println("IO Exception"+ex);
    }
    }
    }
    public void run()
    {
    //read from the server
    String message;
    try
    {
    while((message = is.readLine()) != null)
    {
    System.out.println(message);
    if(message.equals("close"))
    {
    //message equals close terminate the connection
    break;
    }
    }
    if(soc!=null)
    {
    //close the connection
    soc.close();
    System.out.println("connection terminated....");
    System.exit(0);
    }
    end=true;
    }
    catch(IOException x)
    {
    System.out.println("IO Exception "+x);
    }
    }//end of run method
    }//end of main method


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Muliple Client Server chat application..how to send message from server..

    Please edit your post and wrap your code with code tags:
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.


    How have you tried to debug the code so you know what it is doing when it executes? Try adding some more println() statements to print messages at key points in the code and to show the values of variables as the code executes. The print out will help you see what the code is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: Muliple Client Server chat application..how to send message from server..

    Hello.
    Do you have understanding of client/server communication?
    Next, are you familiar with Java API for doing client/server communication - be it one way or two way?
    Try this book: http://www.mdp.ac.id/materi/2012-201...1061-908-1.pdf

    Syed.

  4. #4
    Junior Member
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Muliple Client Server chat application..how to send message from server..

    Hello
    I had an experience by Server/Client and I understood it is too hard.
    The code below is my experience. If you use this code in one station by two cmd window the code works very well. If you use it in two separate stations, your LAN and the windows settings should be OK. In my experience, client code couldn't find the server in some of the stations in my office!
    good lock

    server code:
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
     
    public class TalkServer {
    	private static Scanner ScreenInput;
    	private static ServerSocket SServer;
    	private static Scanner socketIN;
    	public static void main(String[] args)
    	{
    		System.out.println("TalkServer Version 1.0");
    		System.out.print("Type the port: ");
    		ScreenInput = new Scanner(System.in);
    		String sPort=ScreenInput.nextLine();
    		int iPort=Integer.parseInt(sPort);
    		System.out.println("Port Nomber is:"+iPort);
    		System.out.println("Wait for a client...");
     
    		try
    		{
    			SServer = new ServerSocket(iPort);
    			Socket SClient;
    			SClient=SServer.accept();
    			String client;
    			client = SClient.getInetAddress().toString();
    			System.out.println("Connected to " + client);
    			socketIN = new Scanner(SClient.getInputStream());
    			PrintWriter SocketOut;
    			SocketOut=new PrintWriter(SClient.getOutputStream(),true);
    			while (true)
    			{
    				System.out.print("Listening for Client:");
    				String sInput=socketIN.nextLine();
    				System.out.println(sInput);
    				SocketOut.println("Server:"+sInput);
    				if (sInput.equalsIgnoreCase("bye"))
    					break;
    			}
    			SClient.close();
    			SServer.close();
    			System.out.println("Server closed");
    		}
    		catch(Exception e)
    		{
    			e.printStackTrace();
    			System.out.println("Error in connection");
    		}
    	}
    }

    Client code:
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
     
    public class TalkClient {
    	private static Scanner keyBoard;
    	private static Scanner socketIN;
     
    	public static void main(String[] args)
    	{
    		System.out.println("TalkClient Version 1.0");
    		System.out.print("Type the port:");
    		keyBoard = new Scanner(System.in);
    		String sPort=keyBoard.nextLine();
    		int iPort=Integer.parseInt(sPort);
    		System.out.println("Port Nomber is "+iPort);
    		System.out.print("Type the Host:");
    		String sHost=keyBoard.nextLine();
    		Socket s;
    		InetAddress ip;
    		try
    		{
    			ip=InetAddress.getByName(sHost);
    			System.out.println("This Host has The IPs below:");
    			InetAddress[] address=InetAddress.getAllByName(sHost);
    			for (InetAddress iIP: address)
    				System.out.println(iIP.toString());
    			System.out.println("Now Connecting to the Server...");
    			s=new Socket(ip,iPort);
    			System.out.println("Connected to "+iPort);
    			socketIN = new Scanner(s.getInputStream());
    			PrintWriter SocketOut;
    			SocketOut=new PrintWriter(s.getOutputStream(),true);
    			while(true)
    			{
    				System.out.print("Say something:");
    				String sSay=keyBoard.nextLine();
    				SocketOut.println(sSay);
    				String sListen=socketIN.nextLine();
    				System.out.println("check back:"+sListen);
    				if (sSay.equalsIgnoreCase("bye")) break;
    			}
    		}
    		catch (UnknownHostException e)
    		{
    			System.out.println("the hos t is unknown");
    		}
    		catch (IOException e)
    		{
    			System.out.println("Netwerk Error");
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    	}
    }

Similar Threads

  1. Client Server Chat application
    By twolohan in forum What's Wrong With My Code?
    Replies: 1
    Last Post: March 30th, 2013, 06:58 AM
  2. Replies: 0
    Last Post: May 31st, 2012, 05:35 PM
  3. Simple client-server chat program
    By Saloni Patil in forum Java Networking
    Replies: 3
    Last Post: October 22nd, 2011, 09:29 AM
  4. Server-Client Chat application using UDP
    By weakprogrammer in forum Java Networking
    Replies: 3
    Last Post: July 1st, 2011, 02:35 PM
  5. [SOLVED] Server Client does not send file
    By Kakashi in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 10th, 2011, 12:38 PM

Tags for this Thread