Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


JAVA - Connecting multiple clients to a server


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
4 replies to this topic

#1 HelloSkitty   Members   -  Reputation: 152

Like
0Likes
Like

Posted 13 January 2012 - 10:41 PM

So as the title, says, I am trying to connect multiple clients to one server. The following code I partially wrote and partially borrowed works when the Server code is run first, and then one instance of the Client program is run. Both people can click at the screen and make dots appear on the other screen.

However, when I try to run a second Client program, it does not sync with the Server. I tried first killing the first instance of the Client, then pressing "R" on the server (marked as IMPORTANT METHOD in the code) to try to set up another connection on the 100th port, but the second Client still could not connect. Am I doing something wrong?

I think the problem has something to do with my lack of multithreading, but I'm not sure (I don't exactly know how to do multithreading either).


import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
public class MyClient extends JFrame implements MouseListener {
Socket s;
BufferedReader br;
BufferedWriter bw;
ArrayList<Point> points=new ArrayList<Point>();
Image i=null;
public static void main(String args[]) {
  new MyClient();
}
public void run()
{
  try{s.setSoTimeout(1);}catch(Exception e){}
  i=createImage(400,400);
  while (true)
  {
   try{
   draw();
   String s=br.readLine();
   System.out.println(s);
   if (s.charAt(0)=='C') {
    points=new ArrayList<Point>();
   }
   if (s.charAt(0)=='Q') {
    System.exit(0);
   }
   if (s!=null && !s.equals("")) {
    StringTokenizer stk=new StringTokenizer(s);
    points.add(new Point(Integer.parseInt(stk.nextToken()),Integer.parseInt(stk.nextToken())));
   }
   }catch (Exception e){}
  }
}

public void draw() {
  Graphics g=i.getGraphics();
  g.setColor(Color.WHITE);
  g.fillRect(0,0,400,400);
  g.setColor(Color.RED);
  for (int pc=0;pc<points.size();pc++) {
   Point p=points.get(pc);
   g.fillRect((int)p.getX(),(int)p.getY(),3,3);
  }
  Graphics g2=this.getGraphics();
  g2.drawImage(i,0,0,null);
}

public MyClient()
{
  try{
   s = new Socket("192.168.1.5",100);
   br = new BufferedReader(new InputStreamReader(s.getInputStream()));
   bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
  }catch(Exception e){}
  this.setSize(400,400);
  this.addMouseListener(this);
  this.setVisible(true);
  run();
}

public void write(String s) {
  try {bw.write(s);
  bw.newLine();
  bw.flush();} catch(Exception e) {}
}

public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public void mousePressed(MouseEvent e) {
  int x=e.getX(),y=e.getY();
  System.out.println("MOUSE"+x+""+y);
  points.add(new Point(x,y));
  write(x+" "+y);
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

}

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import javax.swing.JFrame;
public class MyServerApp extends JFrame implements MouseListener, KeyListener {

ServerSocket s;
Socket s1;
BufferedReader br;
BufferedWriter bw;
ArrayList<Point> points=new ArrayList<Point>();
Image i=null;

public void run()
{
  try{s1.setSoTimeout(1);}catch(Exception e){}
  i=createImage(400,400);
  while (true)
  {
   try{
   draw();
   String s=br.readLine();
   if (s!=null && !s.equals("")) {
    StringTokenizer stk=new StringTokenizer(s);
    points.add(new Point(Integer.parseInt(stk.nextToken()),Integer.parseInt(stk.nextToken())));
   }
   }catch (Exception e){}
  }
}

public void draw() {
  Graphics g=i.getGraphics();
  g.setColor(Color.WHITE);
  g.fillRect(0,0,400,400);
  g.setColor(Color.RED);
  for (int pc=0;pc<points.size();pc++) {
   Point p=points.get(pc);
   g.fillRect((int)p.getX(),(int)p.getY(),3,3);
  }
  Graphics g2=this.getGraphics();
  g2.drawImage(i,0,0,null);
}

public static void main(String arg[])
{
  new MyServerApp();
}

public void write(String s) {
  try {bw.write(s);
  bw.newLine();
  bw.flush();} catch(Exception e) {}
}

public MyServerApp()
{
  makeConnection();
  this.setSize(400,400);
  this.addMouseListener(this);
  this.addKeyListener(this);
  this.setVisible(true);
  run();
}

public void makeConnection() { // THE IMPORTANT METHOD
  try{
   s = new ServerSocket(100);
   s1=s.accept();
   br = new BufferedReader(new InputStreamReader(s1.getInputStream()));
   bw = new BufferedWriter(new OutputStreamWriter(s1.getOutputStream()));
   bw.write("Hello");bw.newLine();bw.flush();
  }catch(Exception e){}
}

public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public void mousePressed(MouseEvent e) {
  int x=e.getX(),y=e.getY();
  points.add(new Point(x,y));
  write(x+" "+y);
}

public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}

public void keyPressed(KeyEvent e) {
  if (e.getKeyCode()==KeyEvent.VK_SPACE) {
   write("C");
   points=new ArrayList<Point>();
  }
  if (e.getKeyCode()==KeyEvent.VK_Q) {
   write("Q");
  }
  if (e.getKeyCode()==KeyEvent.VK_R) {
   makeConnection();
  }
}

public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}

}

A penny for my thoughts? Do you think I have only half a brain?

Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/

Sponsor:

#2 6510   Members   -  Reputation: 151

Like
0Likes
Like

Posted 14 January 2012 - 03:10 AM

Your server is a one-client-server as you only have client socket variable. Additionally, in each call of makeConnection() you create a new server socket - that should only happen once, at startup e.g.

#3 Antheus   Members   -  Reputation: 2397

Like
1Likes
Like

Posted 14 January 2012 - 08:55 AM

When you .accept() a socket, you get a per-client connection. So each client you want to handle on server needs one of those. Right now, there is only s1.

I think the problem has something to do with my lack of multithreading


Yes and no. Threads aren't required by far to do networking. They were strictly forbidden up until appearance of Java.

Unfortunately, the default sockets provided by JDK are somewhat tedious to use without due to the way handlers are designed. The alternative, NIO, offers top notch networking, but is a big pain to use.

The usual solution is this:
class ClientHandler  {
  List<String> toSend;
  List<String> received;
  Socket s;
  public ClientHandler(Socket s) {
	this.s = s;
  }
  public void update() {
	int readable = s.getInputStream().available();;
	if (readable > 0) {
	  byte b = new byte[readable];
	  s.getInputStream().read(b);
	  received.add(new String(b));
	}
	int writable = s.getOutputStream().available();
	if (writable > 0) {
	  // same as above
	}
  }
}
...
List<ClientHandler> handlers;
s = new ServerSocket(100);
s.setSoTimeout(5); // wait 5 milliseconds max
while (running) {
  try {
	ClientHandler ch = new ClientHandler(s.accept());
	handlers.add(ch);
  } catch (TimeoutException te) {
	// no new connections in last 5 milliseconds
  }
  for (ClientHandler ch : handlers) {
	ch.update();
	// check if each client received some data during last update
	// remove it from their 'received' and do something useful with it
  }
}

The server repeatedly waits 5 milliseconds for new connections then gives up to allow send/receive code to run.
To send data to specific client, put it into respective ClientHandler's toSend list.
When a socket receives data, it will be available in their 'received' list.

There is no error handling above. Clients are also not checked for disconnection. See the read/write and related documentation on socket and input/output streams to determine how exactly to determine those.

#4 HelloSkitty   Members   -  Reputation: 152

Like
0Likes
Like

Posted 14 January 2012 - 03:05 PM

So if I want to let two clients connect to the server, I'd want an s2 variable also (or just an ArrayList of Sockets)? Would it be on the same port (the sample code I edited used Port 100, but can any arbitrary number be used as a port?)?

Also, what if I wanted only one client to be able to connect to the server at a time? After running the server code, the program hangs up on s.accept() until an instance of the Client is called. So when I kill the client program by pressing "Q", it should erase the connection (should I never recreate an instance of a ServerSocket on the same port?). Then, by pressing "R", make Connection() gets called which re-declares s to erase any trace of a connection (on the same port) and calls s.accept(). This either calls an exception, or the line just carries out, despite the fact that there should be no connection to accept.

How would I make a one-client server that can deal with disconnections?
A penny for my thoughts? Do you think I have only half a brain?

Not-so-proud owner of blog: http://agathokakologicalartolater.wordpress.com/

#5 rip-off   Moderators   -  Reputation: 8527

Like
1Likes
Like

Posted 14 January 2012 - 06:36 PM

So if I want to let two clients connect to the server, I'd want an s2 variable also (or just an ArrayList of Sockets)?


Yes, you would use a collection like ArrayList.

Would it be on the same port


You don't have to worry about ports. When you accept() a client socket, it handles this for you. From the clients point of view, it appears to be connected to the same port that the server is listening on. All the clients appear to have this same view. This is because a TCP connection socket is identified by both its endpoints, that is, the ip-address:port of the client and the ip-address:port of the server.

the sample code I edited used Port 100, but can any arbitrary number be used as a port?

Yes and no. The first restriction is that ports are 16 bit unsigned values, so you cannot have values over 216. Your operating system might impose additional restrictions. For example, most *nix kernels will not allow non-root processes to use any port below 1024.

In general, it is also advised not to use a "well known port" (this is the reason why *nix kernels are finickity about such low value ports). Using the same port number as a common application means that it will be more difficult to run them both on the same machine (the administrator will typically have to get one of the programs to run on a custom port, and configure inbound connections to use this port).

Also, what if I wanted only one client to be able to connect to the server at a time?

Generally, this is a bad idea. For one thing, there are always malicious port scanning processes running on the net. If one of them happens to be scanning for your port (or running a scan against every port), it could connect to your server which would deny you the ability to connect for some time. If you pick a well known port, this is far more likely.

Worst case scenario would be if someone wanted to annoy you, they could hold the connection open and you would suffer a trivial DOS attack.

Why do you want to only support one client at a time?

should I never recreate an instance of a ServerSocket on the same port?

You generally would not. Most server applications do not close their socket for any reason other than shutdown. In addition, unless you use SO_REUSEADDR you may get errors trying to recreate a server socket on the same port.

How would I make a one-client server that can deal with disconnections?

One option is to make a multi-client server. When a connection is fully establised (including maybe an initial protocol handshake), if there is already a connected client then perform a clean close on the socket (optionally leveraging the protocol to deliver a nice error message to the user who's connection is being dropped).




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS