3 Replies - 4437 Views - Last Post: 13 April 2012 - 04:01 AM Rate Topic: -----

#1 hamishehiran  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 73
  • Joined: 03-February 10

Client/Server Threads: messages don't pass properly.

Posted 12 April 2012 - 03:05 PM

Hi,

I'm trying to write a simple chat client program, and in this point I'm just trying to send some info from server to clients. here in the Outgoing inner class( defined in server) I'm trying to print the list of clients connected , and send it to all other clients. clients are saved in the Arraylist named users.
I think I should some how sleep the threads but I don't exactly know when and how. Now nothing is sent to clients from servers (sometimes it does just when I stop the server , and the input shows up in the client console).
Thank you in advance.


Server Code:
import java.net.ServerSocket;

import java.net.Socket;



import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Scanner;


public class Server 

{

	private static final int SERVER_PORT = 6000;
	protected ServerSocket serverSocket;
	protected Socket socket;
	PrintWriter out ;

	private ArrayList<Client> users = new ArrayList<Client>();

	class Incoming extends Thread{

		private Socket socket;
		private int id;

		public Incoming(Socket socket ,int id) {
			// TODO Auto-generated constructor stub

			this.socket=socket;
			this.id=id;
		}



		public void run() {


			try {

				Scanner sc = new Scanner(socket.getInputStream());
				System.out.println("incoming thread");
				//out.print(" Connected Clients:");

				System.out.println( sc.nextLine() );	
				out.print("Client"+id);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println( "Exception while sending to client");
			}

		}
	}

	class Outgoing extends Thread{

		private Socket socket;
		private int id;

		public Outgoing(Socket socket ,int id) {
			// TODO Auto-generated constructor stub

			this.socket=socket;
			this.id=id;
		}


		@Override
		public void run() {
			// TODO Auto-generated method stub


			try {

				PrintStream out = new PrintStream(socket.getOutputStream());
				out.println(" Connected Clients:");
				
				for (int i = 0; i < users.size(); i++) {
					out.println("Client" + i);
				}
			}

			catch (IOException e) {
				// TODO Auto-generated catch block
				System.out.println( "Exception while sending to client");
			}

			//}

		}

	}

	public Server()
	{


		try

		{

			serverSocket = new ServerSocket(SERVER_PORT);
			System.out.println();


		}
		catch(IOException e)

		{

			System.out.println("Could not open server socket.");

			return;

		}

		System.out.println("Socket "+serverSocket+" created.");
		
		go();

	}



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

	}
	public void go()

	{

		System.out.println("Room has been started.");


		System.out.println("Connected Clients:");
		for (int i = 0; i < users.size(); i++) {
			System.out.println( "Client" + users.get(i).id);
		}
		while(true)

		{  
			for(int i = 0;i < users.size();i++){

				if(!users.get(i).isConnected())

				{

					System.out.println(users.get(i)+" removed due to lack of connection.");

					users.remove(i);

				}

				Outgoing outport = new Outgoing(users.get(i).socket , users.get(i).id);
				outport.start();

			}

			try

			{

				socket = serverSocket.accept();



			}

			catch(IOException e)

			{

				System.out.println("Could not get a client.");

			}

			System.out.println("Client "+socket+" has connected." );
			users.add(new Client(socket, 1));

			try

			{
				Thread.sleep(200);

			}

			catch(InterruptedException e)

			{

				System.out.println("Room has been interrupted.");

			}

		}

	}

}









Client code:

import java.net.Socket;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;



public class Client extends Thread
{

	protected Socket socket;
	protected boolean connected;
	protected int id;
	BufferedReader in;


	class Incoming extends Thread{

	
		@Override
		public void run() {

			try

			{
				
				System.out.println("in");
				String msg="";
				in= new BufferedReader( new InputStreamReader(socket.getInputStream()));
				
				while( (msg = in.readLine()) !=null )
					System.out.println( in.readLine() );
				
				System.out.println( "recieved:" + msg);
				System.out.println(socket+" has connected input.");
				
			}

			catch(IOException e)

			{

				System.out.println("Could not get input stream from "+toString());
				return;


			}

		}

	}
	
	public static void main(String[] args) {
		
		try {
			new Client(new Socket("localhost",6000),0).start();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public Client(Socket newSocket , int id)

	{
		
		socket = newSocket;
		connected = true;
		this.id=id;
			}

	public boolean isConnected()

	{

		return connected;

	}

	public void endConnection()

	{

		try{

			connected = false;
			socket.close();

		}

		catch(IOException e)

		{

			System.out.println("Could not end "+socket+".");
			System.out.println();

		}

	}


	public String toString()

	{

		return new String(socket.toString());

	}





	public void run()

	{	

		Incoming input = new Incoming();
		input.start();

		while(true)
		{

			try
			{

				Thread.sleep(200);

			}
			catch(Exception e)
			{

				System.out.println(toString()+" has input interrupted.");

			}
		}
	}
}


This post has been edited by hamishehiran: 12 April 2012 - 11:37 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Client/Server Threads: messages don't pass properly.

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Client/Server Threads: messages don't pass properly.

Posted 12 April 2012 - 08:24 PM

Completly wrong design :) Sorry

The Server should not a Thread.
The Server waits for a Client connection and then spawn a Thread to serve that connection, and then go back to wait for a connection

Very very basic example:
http://www.dreaminco...snippet1917.htm

or a complete chat room
http://www.dreaminco...r-gui-optional/
Was This Post Helpful? 1
  • +
  • -

#3 hamishehiran  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 73
  • Joined: 03-February 10

Re: Client/Server Threads: messages don't pass properly.

Posted 12 April 2012 - 11:29 PM

View Postpbl, on 12 April 2012 - 08:24 PM, said:

Completly wrong design :) Sorry

The Server should not a Thread.
The Server waits for a Client connection and then spawn a Thread to serve that connection, and then go back to wait for a connection

Very very basic example:
http://www.dreaminco...snippet1917.htm

or a complete chat room
http://www.dreaminco...r-gui-optional/


Thank you. At First Server was not a thread but really there was no different in the result. I have created threads for input and outputs. But Considering that Client and Server not be Threads ( changed it in the code) should I create a Thread just for accepting the sockets? I've seen a lot of codes ( also those you suggested) and I know that the Server and Client class doesn't need to be a thread, but I don't know how many threads are needed for my particular program.
Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8343
  • View blog
  • Posts: 31,890
  • Joined: 06-March 08

Re: Client/Server Threads: messages don't pass properly.

Posted 13 April 2012 - 04:01 AM

View Posthamishehiran, on 13 April 2012 - 02:29 AM, said:

Thank you. At First Server was not a thread but really there was no different in the result. I have created threads for input and outputs. But Considering that Client and Server not be Threads ( changed it in the code) should I create a Thread just for accepting the sockets?

No.

Server:
   while(true);
     Socket s = serverSocket.acceptConnection();
     new ServeurThreadToDialogWithClient(s).start();
   }



[quote]
I've seen a lot of codes ( also those you suggested) and I know that the Server and Client class doesn't need to be a thread, but I don't know how many threads are needed for my particular program.
[/code]
Server run
Fire one thread for each Client connected
That thread might fire another one if you want to split two different threads one for input one for output

Client run.
Might fire another thread if you want to separate inut/output

So a maximum of 2 threads per connection:
2 on the server side
1 one the client side.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1