• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
HelloSkitty

JAVA - Connecting multiple clients to a server

4 posts in this topic

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).


[CODE]
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) {}

}
[/CODE]

[CODE]
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) {}

}
[/CODE]
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.

[quote]I think the problem has something to do with my lack of multithreading[/quote]

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:[code]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
}
}[/code]

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.
1

Share this post


Link to post
Share on other sites
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?
0

Share this post


Link to post
Share on other sites
[quote]
[color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif][size=3][left]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)?[/left][/size][/font][/color]
[/quote]
Yes, you would use a collection like ArrayList.

[quote]
[color=#282828][font=helvetica, arial, verdana, tahoma, sans-serif][size=3][left]Would it be on the same port [/left][/size][/font][/color]
[/quote]
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 [b]both its endpoints[/b], that is, the ip-address:port of the client [b]and [/b]the ip-address:port of the server.

[quote]
the sample code I edited used Port 100, but can any arbitrary number be used as a port?
[/quote]
Yes and no. The first restriction is that ports are 16 bit unsigned values, so you cannot have values over 2[sup]16[/sup]. 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 "[url="http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports"]well known port[/url]" (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).

[quote]
Also, what if I wanted only one client to be able to connect to the server at a time?
[/quote]
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?

[quote]
should I never recreate an instance of a ServerSocket on the same port?
[/quote]
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.

[quote]
How would I make a one-client server that can deal with disconnections?
[/quote]
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).
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0