More than 1 connection

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 1185 Views - Last Post: 19 December 2007 - 01:14 PM Rate Topic: -----

#1 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

More than 1 connection

Posted 18 December 2007 - 01:03 AM

Hi all,

I'm currently working on a kind of chat program based on this tutorial:

http://www.dreaminco...wtopic38672.htm


Well, i got this now as my server:

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.*;

public class ServerTest
{

	public ServerSocket serverSocket;
	public Socket clientSocket;
	public BufferedReader bufferedReader;
	public String inputLine;

	public static void main(String[] args)
	{
		ServerTest test = new ServerTest();
	}

	public ServerTest()
	{
		// Wachten op de client om te connecten met poort 10005
		try
		{
			serverSocket = new ServerSocket(10005);
			clientSocket = serverSocket.accept();
			// Maakt een reader

			bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			// Ontvangen bericht client
			while((inputLine = bufferedReader.readLine()) != null)
			System.out.println(inputLine);
		}
		catch(IOException e)
		{
			System.out.println(e);
		}

	}

}



And this as my client:

import java.net.Socket;
import java.io.PrintWriter;
import java.io.*;

public class ClientTest
{
	private static Socket socket;
	private static PrintWriter printWriter;

	private static BufferedReader myIn = new BufferedReader(new InputStreamReader(System.in));
	private static String message;

	public static void main(String[] args)
	{

		{
			try
			{
				socket = new Socket("localhost",10005);
				while(true) {
				printWriter = new PrintWriter(socket.getOutputStream(),true);
				System.out.print(": ");
				System.out.flush();
				message = myIn.readLine();
				printWriter.println(message);
				}

			}
			catch(Exception e)
			{
				System.out.println(e);
			}
		}
	}
}



It works all perfect, but the problem now is: it can only connect with 1 client. I tried already something with threads, but it didn't help at all...

So if someone knows how i can get the server accepts more connections, thank you.

Sorry for my bad english.

Is This A Good Question/Topic? 0
  • +

Replies To: More than 1 connection

#2 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 03:21 AM

The standard way of having a server application accept multiple connections on the same port is to have the server listen to the port and when an incoming connection request is detected, assign that connection a new port (different from the one your app is using) and spin it off into a new Thread. In order to control resource usage it's advisable to use a static Thread pool for these connections. Look at the java.concurrency package to the Executor class. It has some static methods for creating a static Thread pool. Set the thread pool to the maximum number of concurrent connections you'll accept. So...pseudocode:

T <-- static ThreadPool, size N

conditional_loop
{
	wait for connection on port X
	when incoming connection(X) from client C detected
	{
		if T has threads available
		{
			get Thread t from T
			assign C new port number
			run C on thread t
		}
		else
			reject connection
	}
}


The basic idea is that when you assign a new port and thread to the incoming connection, you relinquish your main port and continue listening for new connections.

This post has been edited by Programmist: 18 December 2007 - 03:23 AM

Was This Post Helpful? 0
  • +
  • -

#3 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: More than 1 connection

Posted 18 December 2007 - 03:55 AM

Or write an UDP based protocol, that way you only need one port, but you have to do a lot of stuff yourself (making sure that packets are transmitted (they can get lost with UDP), check their order because one that is sent later can arrive sooner, etc.
Anyway, you are probably better off with the way programmist suggested, because for chat programs that is just enough, and that is the common practice :)
Was This Post Helpful? 0
  • +
  • -

#4 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 08:00 AM

View Post1lacca, on 18 Dec, 2007 - 04:55 AM, said:

Or write an UDP based protocol, that way you only need one port, but you have to do a lot of stuff yourself (making sure that packets are transmitted (they can get lost with UDP), check their order because one that is sent later can arrive sooner, etc.
Anyway, you are probably better off with the way programmist suggested, because for chat programs that is just enough, and that is the common practice :)

Heck, if you're going to write your own transport protocol, why stop there? While you're at it you can write your own JVM. Then you can create your own operating system. :) lol
Was This Post Helpful? 0
  • +
  • -

#5 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 18 December 2007 - 08:53 AM

well, i'm not that skilled, but 1lacca can try :D

but well, i'll try your example Programmist - i'm not really good in reading pseudo-code, but i'll do my best ;)

This post has been edited by nbarten: 18 December 2007 - 08:55 AM

Was This Post Helpful? 0
  • +
  • -

#6 1lacca  Icon User is offline

  • code.rascal
  • member icon

Reputation: 44
  • View blog
  • Posts: 3,822
  • Joined: 11-August 05

Re: More than 1 connection

Posted 18 December 2007 - 09:23 AM

View PostProgrammist, on 18 Dec, 2007 - 04:00 PM, said:

View Post1lacca, on 18 Dec, 2007 - 04:55 AM, said:

Or write an UDP based protocol, that way you only need one port, but you have to do a lot of stuff yourself (making sure that packets are transmitted (they can get lost with UDP), check their order because one that is sent later can arrive sooner, etc.
Anyway, you are probably better off with the way programmist suggested, because for chat programs that is just enough, and that is the common practice :)

Heck, if you're going to write your own transport protocol, why stop there? While you're at it you can write your own JVM. Then you can create your own operating system. :) lol


"Real men have fabs" , so I guess I'll start right at the CPU level. Sun has just opensourced the Niagara anyway, but probably I should start on my own. Actually, these atom things are quite outdated, maybe I should make some minor changes at that level as well.
Was This Post Helpful? 0
  • +
  • -

#7 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 09:49 AM

View Post1lacca, on 18 Dec, 2007 - 10:23 AM, said:

"Real men have fabs" , so I guess I'll start right at the CPU level. Sun has just opensourced the Niagara anyway, but probably I should start on my own. Actually, these atom things are quite outdated, maybe I should make some minor changes at that level as well.

I guess god is the ultimate developer then. :)

View Postnbarten, on 18 Dec, 2007 - 09:53 AM, said:

...i'm not really good in reading pseudo-code, but i'll do my best ;)

Just look around in the Java API (also use Google) and soon you'll find the things you need to turn the pseudo-code into actual code. Just think about each line, what it's doing, and try to relate it to something Java-related.

This post has been edited by Programmist: 18 December 2007 - 09:50 AM

Was This Post Helpful? 0
  • +
  • -

#8 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 18 December 2007 - 12:47 PM

It's working now :) Thanks for your advice.

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.*;

public class ServerTest
{

	public static void main(String[] args) throws IOException
	{

		// Wachten op de client om te connecten met poort 10005
		ServerSocket serverSocket = new ServerSocket(10005);
		System.out.println("Server running...");

		while(true)
		{
			// wachten tot er een client connect
			Socket clientSocket = serverSocket.accept();
			System.out.println(clientSocket.getInetAddress().getHostName() + " connected");

			// nieuwe thread maken
			new ThreadHandler(clientSocket);
		}

	}

}

class ThreadHandler implements Runnable
{
	public Thread activiteit = new Thread(this);
	Socket s;
	public BufferedReader bufferedReader;
	public String inputLine;

	public ThreadHandler(Socket so) throws IOException
	{
		s = so;
		// Maakt een reader
		bufferedReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
		activiteit.start(); // thread starten
	}

	public void run() {

		while(true)
		{
			try
			{
				// Ontvangen bericht client
				while((inputLine = bufferedReader.readLine()) != null)
				System.out.println(inputLine);
				/*
				if(inputLine == "exit")
				{
					s.close();
				}
				*/
			}
			catch(IOException e)
			{
				break;
			}



		}

		System.out.println(s.getInetAddress().getHostName() + "disconnected");

		try
		{
			s.close();
		}
		catch (IOException e)
		{
		}

	}

}



Just one more thing... i thought of this idea: a client sends a message to the server. Then the server sends the message to all clients currently connected (maybe putting al connected sockets in an array?) and then the client display the message....

But how can i realize that? I mean, all the way the client is waiting for the user to type some text and hit the Enter-button... so how can it display the message after that? (in dos of course)
Was This Post Helpful? 0
  • +
  • -

#9 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 01:13 PM

View Postnbarten, on 18 Dec, 2007 - 01:47 PM, said:

It's working now :) Thanks for your advice.

...

Just one more thing... i thought of this idea: a client sends a message to the server. Then the server sends the message to all clients currently connected (maybe putting al connected sockets in an array?) and then the client display the message....

But how can i realize that? I mean, all the way the client is waiting for the user to type some text and hit the Enter-button... so how can it display the message after that? (in dos of course)

Glad it's working.

What you're describing in the first paragraph is broadcasting from one client to all clients. You can do this the way you described, or if you want to be slick you can use the Observer design pattern (Google).

To address your second question - is your client using one or two Threads?

This post has been edited by Programmist: 18 December 2007 - 01:13 PM

Was This Post Helpful? 0
  • +
  • -

#10 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 18 December 2007 - 01:31 PM

just 1 - it's still the same as i posted in code in my first post in this topic.
Was This Post Helpful? 0
  • +
  • -

#11 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 02:42 PM

View Postnbarten, on 18 Dec, 2007 - 02:31 PM, said:

just 1 - it's still the same as i posted in code in my first post in this topic.

Ok. I was kinda trying to give you a hint. Didn't work. :) How can your code block while waiting on input from the user and also wait on input from the server, using just one thread?
Was This Post Helpful? 0
  • +
  • -

#12 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 18 December 2007 - 02:49 PM

you mean i must use 2 threads for the client? and then i wonder where the message the server sends will be printed. Below the input? (and still be able to type something?)
Was This Post Helpful? 0
  • +
  • -

#13 Programmist  Icon User is offline

  • CTO
  • member icon

Reputation: 249
  • View blog
  • Posts: 1,829
  • Joined: 02-January 06

Re: More than 1 connection

Posted 18 December 2007 - 03:07 PM

View Postnbarten, on 18 Dec, 2007 - 03:49 PM, said:

you mean i must use 2 threads for the client? and then i wonder where the message the server sends will be printed. Below the input? (and still be able to type something?)

Since you're using the console to both send and receive messages, you might experience a "disruption" if a message is received while you are typing. If it were two separate processes, then you'd have problems and have to run one of them in the background. But I think that you should be able to do it with one process that has two threads. If it works, it probably won't be pretty though. Try it. By the way - why don't aren't you doing this with a GUI?
Was This Post Helpful? 0
  • +
  • -

#14 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 18 December 2007 - 03:38 PM

ah well.... i just liked to try it first without a GUI... :P i just wanted to build the connection first between the server and the client.

Anyway thanks :D
Was This Post Helpful? 0
  • +
  • -

#15 nbarten  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 162
  • Joined: 30-April 07

Re: More than 1 connection

Posted 19 December 2007 - 09:19 AM

Well... i got another problem. I know, i'm irritating...

first the code of the server:

import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.*;

public class ServerTest
{


	public static void main(String[] args) throws IOException
	{
		Socket[] allSockets = new Socket[10]; // 10 is maximum aantal clients
		int clientsConnected = 0;
		// Wachten op de client om te connecten met poort 10005
		ServerSocket serverSocket = new ServerSocket(10005);
		System.out.println("Server running...");

		while(true)
		{
			// wachten tot er een client connect
			Socket clientSocket = serverSocket.accept();
			clientsConnected++;
			allSockets[clientsConnected-1] = clientSocket;
			//System.out.println(clientSocket.getInetAddress().getHostName() + " connected");
			for(int i=0; i<clientsConnected; i++)
			{
				System.out.print(allSockets[i]);
				System.out.flush();
			}
			// nieuwe thread maken
			new ThreadHandler(clientSocket);
		}

	}

}

class ThreadHandler implements Runnable
{
	public Thread activiteit = new Thread(this);
	Socket s;

	public BufferedReader bufferedReader;
	public String inputLine;

	public ThreadHandler(Socket so) throws IOException
	{
		s = so;

		// Maakt een reader
		bufferedReader = new BufferedReader(new InputStreamReader(s.getInputStream()));
		activiteit.start(); // thread starten
	}

	public void run() {

		while(true)
		{
			try
			{
				// Ontvangen bericht client
				while((inputLine = bufferedReader.readLine()) != null)
				System.out.println(inputLine);
				/*
				if(inputLine == "exit")
				{
					s.close();
				}
				*/
				//System.out.println(allSockets[0]);
			}
			catch(IOException e)
			{
				break;
			}



		}

		System.out.println(s.getInetAddress().getHostName() + "disconnected");

		try
		{
			s.close();
		}
		catch (IOException e)
		{
		}

	}

}



In the main i create an array 'allSockets', where Sockets can be stored. Everytime a client connect, the socket of the new client is stored in the array allSockets.

My problem is, the 'message-accepting' (and printing on the screen of the message) is done by the class ThreadHandler. So, after it prints the message on the screen of the server (string inputLine) i wanted to use the allSockets array to send the message to all clients. The problem is, i cant use the array in that class.

I already thought of sending the array with the new object of class ThreadHandler if a new thread is made (like clientSocket), but every thread then would have another array of 'allSockets'?? (different size, because later/earlier connected than other clients).

I'm often have this kind of problems... using a variabele or array in another class isn't working.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2