5 Replies - 227 Views - Last Post: 02 November 2017 - 05:44 AM Rate Topic: -----

#1 Shaedowhunter  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-November 17

Server/Client UDP game error in code

Posted 02 November 2017 - 05:17 AM

Hi guys, so I've tried several attempts to get the connection between the Client and Server working, but to no avail. Is anyone able to diagnose the problem? I've tried debugging using IntelliJ but I'm not that great at the debugging side (and from what I saw it didn't show much, no error). Basically this is like the Tron game (like Snake.io but without the eating), and the main problem I'm getting is that I want users to appear on the same screen, and their movements tracked. However I can't get either.
Thanks heaps

Client.java

import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class Client extends Applet implements Runnable{

    JFrame frame;
    static Socket socket;
    static DataInputStream in;
    static DataOutputStream out;
    static int playerId;
    int[] x = new int[10];
    int[] y = new int[10];


    public void init(){
        try {
            System.out.println("Connecting");
            socket = new Socket("localhost", 7777);
            System.out.println("Connection successful.");
            JOptionPane.showMessageDialog(frame,
                    "Connection successful");
            in = new DataInputStream(socket.getInputStream());
            playerId = in.readInt();
            out = new DataOutputStream(socket.getOutputStream());
            Input input = new Input(in, this);
            Thread thread = new Thread(input);
            thread.start();
            Thread thread2 = new Thread(this);
            thread2.start();
        }
        catch (Exception e){
            System.out.println("Unable to start client");
        }
    }

    public void updateCoordinates(int pid, int x2, int y2){
        this.x[pid] = x2;
        this.y[pid] = y2;
    }
    public void actionPerformed(ActionEvent e) {
    }
    public static void main(String[] args) {
    JFrame frame = new JFrame("Light Cycles");
    Display display = new Display();
    LightCycle lightCycle = new LightCycle(100, Color.blue);
    Timer timer = new Timer(24, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            lightCycle.move(display.getSize());
            if (lightCycle.isWallActive()) {
                ArrayList<Rectangle> rect = lightCycle.getTrail();
                rect.add(new Rectangle(lightCycle.getX(), lightCycle.getY(), 30,30 ));
                lightCycle.setTrail(rect);
            }
            lightCycle.move(display.getSize());
            if (!lightCycle.isActive){
                display.gameOver();
            }

            display.repaint();
        }
    });
        timer.start();
         display.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println(e.getKeyCode());
                //press 'W' to go up
                if (e.getKeyCode() == 87) {
                    lightCycle.yDir = -1;
                    lightCycle.xDir = 0;

                }
                //press 'S' to go down
                if (e.getKeyCode() == 83) {
                    lightCycle.yDir = 1;
                    lightCycle.xDir = 0;
                }
                //press 'A' to go left
                if (e.getKeyCode() == 65) {
                    lightCycle.yDir = 0;
                    lightCycle.xDir = -1;
                }
                //press 'D' to go right
                if (e.getKeyCode() == 68) {
                    lightCycle.yDir = 0;
                    lightCycle.xDir = 1;
                }
                //spacebar toggling jet wall
                if (e.getKeyCode() == 32) {
                    lightCycle.jetWall();
                }
                //Shift key increases speed
                if (e.getKeyCode() == 16) {
                    lightCycle.speed = lightCycle.speed + 1;
                }
                //'Z' key decreases speed
                if (e.getKeyCode() == 90) {
                    lightCycle.speed = lightCycle.speed - 1;
                }
                if (lightCycle.isActive) {
                    try {
                        //out.writeInt(playerId);
                        out.writeInt(lightCycle.xDir);
                        out.writeInt(lightCycle.yDir);
                        out.writeInt(lightCycle.speed);
                        //out.writeInt(lightCycle.isWallActive);
                    } catch (Exception e1) {
                        System.out.println("Error sending coordinates");
                    }
                }
            }
        });

/*____________________________Application window's sizing permissions/properties____________________________________*/
        frame.add(display, BorderLayout.CENTER);

        display.setLightCycle(lightCycle);

        frame.pack();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        //    frame.setResizable(false);
    }


    public void run(){
        while(true){

            try{
                Thread.sleep(400);
            }
            catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class Input implements Runnable {
    DataInputStream in;
    Client client;
    public Input(DataInputStream in, Client c){
        this.in = in;
        this.client = c;
    }
    public void run(){
        while (true){
            String message;
            try {
                int playerId = in.readInt();
                int x = in.readInt();
                int y = in.readInt();
                client.updateCoordinates(playerId, x, y);
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
    }
}



Server.java

import java.io.*;
import java.net.*;

public class Server {
    static ServerSocket serverSocket;
    static Socket socket;
    static DataOutputStream out;
    static Users[] user = new Users[20];
    static DataInputStream in;

    public static void main(String[] args) throws Exception {
        System.out.println("Starting Server...");
        serverSocket = new ServerSocket(7777);
        System.out.println("Server started.");
        while (true) {
            socket = serverSocket.accept();
            for (int i = 3; i < 20; i++) {
                if (user[i] == null){
                    out = new DataOutputStream(socket.getOutputStream());
                    in = new DataInputStream(socket.getInputStream());
                    user[i] = new Users(out, in, user, i);
                    Thread thread = new Thread(user[i]);
                    thread.start();
                    break;
                }
                //out.writeUTF("This is a test of Java sockets.");
                //System.out.println("Data has been sent.");
            }
        }
    }

    static class Users implements Runnable {

        DataOutputStream out;
        DataInputStream in;
        Users[] user = new Users[20];
        String name;
        int playerId;
        int playerIdIn;
        int xIn;
        int yIn;

        public Users(DataOutputStream out, DataInputStream in, Users[] user, int pid) {
            this.out = out;
            this.in = in;
            this.user = user;
            this.playerId = pid;
        }

        @Override
        public void run() {
            try {
                //name = in.readUTF();
                out.writeInt(playerId);
            } catch (IOException e) {
                System.out.println("Failed to send Player ID.");
                e.printStackTrace();
            }
            while (true) {
                try {
                    playerIdIn = in.readInt();
                    xIn = in.readInt();
                    yIn = in.readInt();
                    for (int i = 3; i < 20; i++) {
                        if (user[i] != null) {
                            user[i].out.writeInt(playerIdIn);
                            user[i].out.writeInt(xIn);
                            user[i].out.writeInt(yIn);
                        }
                    }
                }
                catch (IOException e){
                    e.printStackTrace();
                    user[playerId] = null;
                }
            }
        }
    }
}



LightCycle.java

import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.image.*;


class LightCycle {
    private int x, y;
    int xDir, yDir;

    private int size;
    int speed;
    private Color color;

    public boolean isActive;
    public boolean isWallActive = false;
    private boolean isSpeedy = false;
    private ArrayList<Rectangle> trail = new ArrayList<Rectangle>();

    int speedCount;
    public int getY() {
        return y;
    }
    public int getX() {
        return x;
    }
    public boolean isWallActive() {
        return isWallActive;
    }
    public ArrayList<Rectangle> getTrail() {
        return trail;
    }
    public void setTrail(ArrayList<Rectangle> trail) {
        this.trail = trail;
    }


/*_____________________________Light Cycle properties____________________________________*/
    LightCycle(int size, Color color) {
        isActive = true;
        x = 100;
        y = 300;
        xDir = 0;
        yDir = 0;
        speed = 0;
        this.size = size;
        this.color = Color.blue;
    }


    void speedReset(){
      //  speedCount = 0;
    }

    /*_________________________Toggles speed________________________________________
    void speedStat() {
        if (!isSpeedy && (speedCount == 0 || speedCount == -1)){
            speedUp();
            speedUp();
            isSpeedy = true;
            speedCount += 1;
        }
        if (speedCount == 1){
            slowDown();
            isSpeedy = false;
            speedCount -= 1;
        }
        if (!isSpeedy && speedCount == -1 ){
            speedUp();
            speedUp();
            speedCount = 0;
            isSpeedy = true;
       }
    }*/

    /*__________________________Movement Speed_______________________________________*/
    /*void speedUp() {
        xDir *= 2;
        yDir *= 2;
    }
    void slowDown() {
        xDir /= 2;
        yDir /= 2;
    }*/


/*_______________________________Toggling Jet Wall__________________________________*/

    void jetWall() {
        if (isWallActive == true) {
            isWallActive = false;
            System.out.println("Jetwall is off");
        } else {
            isWallActive = true;
            System.out.println("Jetwall is on");
        }
    }


/*____________________________Border collisions_____________________________________*/
    void move(Dimension size) {
        x = x + xDir * speed;
        y = y + yDir * speed;


        if ((xDir > 0 && x + this.size / 2 > size.width)) {
            xDir = 0;
            yDir = 0;
            x -= 5;
            isActive = false;
        }
        if ((xDir < 0 && x - this.size / 7 < 0)) {
            xDir = 0;
            yDir = 0;
            x += 5;
            isActive = false;
        }
        if ((yDir > 0 && y + this.size / 2 > size.height)) {
            xDir = 0;
            yDir = 0;
            y -= 5;
            isActive = false;
        }
        if ((yDir < 0 && y - this.size < 0)) {
            xDir = 0;
            yDir = 0;
            y += 5;
            isActive = false;
        }
    }

/*_____________________________Creates Light Cycle sprite____________________________________*/
    void draw(Graphics graphics) {
        int topLeftX = x - 2;
        int topLeftY = y - 2;



        Graphics localGraphics = graphics.create();
        localGraphics.setColor(color);
        localGraphics.fillRect(topLeftX, topLeftY,
                30, 30);
        localGraphics.drawRect(topLeftX, topLeftY, 30, 30);
        localGraphics.dispose();

    }
}



GameMenu.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class GameMenu extends JFrame {

    private GameMenu(){
        super("Start Menu");
        setVisible(true);
        GridLayout gridLayout = new GridLayout(6,1);
        Container container = getContentPane();
        JButton button = new JButton("Play Game");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Client.main(null);
                setVisible(false);
            }
        });

        JButton instructionButton = new JButton("Instructions");
        instructionButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e1) {
                GameInstructions.main(null);
            }
        });


        container.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT));
        container.add(instructionButton);
        container.add(button);
    }


    public static void main(String[] args) {
        GameMenu mainMenu = new GameMenu();
        mainMenu.setSize(new Dimension(600, 800));
        mainMenu.setLocationRelativeTo(null);
        mainMenu.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        mainMenu.setVisible(true);

    }
}



GameInstructions.java

import javax.swing.*;

public class GameInstructions extends JFrame {
static JFrame frame;

    public static void main(String[] args) {
        JOptionPane.showMessageDialog(frame,
                "Use the WASD keys to move \nUse the Space Bar to toggle your Jet wall" +
                        "\nUse the Left Shift key to speed up\nUse the 'Z' key to slow down",
                "Game Instructions",
                JOptionPane.PLAIN_MESSAGE);
    }
}



Display.java

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;

public class Display extends JPanel {

    boolean isActive;
    private LightCycle lightCycle;
    private static final Random random = new Random();
    private static final Font font = new Font("Calibri", Font.BOLD, 50);
    int collision = 0;
    JFrame frame;


    void setLightCycle(LightCycle lightCycle) {
        this.lightCycle = lightCycle;
    }

    public void gameOver() {
        isActive = false;
    }

    /*______________________________Application window's properties___________________________________*/
    Display() {
        setFocusable(true);
        setPreferredSize(new Dimension(600, 800));
        setBackground(new Color(0, 0, 0));
        isActive = true;
    }

    /*____________________________Jet Wall properties_____________________________________*/
    @Override
    protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

        ArrayList<Rectangle> rects = lightCycle.getTrail();
        for (Rectangle rectangle : rects) {
            graphics.setColor(Color.RED);
            graphics.drawRect(rectangle.x - 2, rectangle.y - 2, 30, 30);
            graphics.fillRect(rectangle.x - 2, rectangle.y - 2, 30, 30);
        }

/*_______________________Checks if the Light Cycle sprite hasn't collided with any objects_________________________________*/
        if (isActive) {
            if (lightCycle != null) {
                lightCycle.draw(graphics);
            }
        } else {
            collision += 1;
        }
        if (collision == 1) {
            int replayOptionBox = JOptionPane.showConfirmDialog(frame,
                    "Do you want to play again?");
            if (replayOptionBox == JOptionPane.YES_OPTION) {
                JOptionPane.showMessageDialog(null, "Finding another player...");
                Client.main(new String[0]);
                setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null, "Returning to Menu...");
                try {
                    GameMenu.main(new String[0]);
                    setVisible(false);
                } catch (Exception e) {
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null, "Error: can not return to menu");
                    System.exit(0);
                }

            }
        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Server/Client UDP game error in code

#2 Radius Nightly  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 88
  • Joined: 07-May 15

Re: Server/Client UDP game error in code

Posted 02 November 2017 - 05:24 AM

Im not into Java, but i see localhost, are you sure this two gamers are connected to the right server? It looks to me that each one are connected to itself. Does connection between them works outside the game? Are clients in local network or online?
Port are set, probably your favorite number, but lots of ports can be blocked by default standards. For example 44777 is a big one well known for virus transfers. Try to enable UPNP everywhere to get port opened on request, in lots of routers its turned off by default.

This post has been edited by Radius Nightly: 02 November 2017 - 05:27 AM

Was This Post Helpful? 0
  • +
  • -

#3 Shaedowhunter  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-November 17

Re: Server/Client UDP game error in code

Posted 02 November 2017 - 05:28 AM

View PostRadius Nightly, on 02 November 2017 - 05:24 AM, said:

Im not into Java, but i see localhost, are you sure this two gamers are connected to the right server? Does connection between them works outside the game? Are clients in local network or online?
Port are set, probably your favorite number, but lots of ports can be blocked by default standards. For example 44777 is a big one well known for virus transfers. Try to enable UPNP everywhere to get port opened on request, in lots of routers its turned off by default.

I'm aiming for them to be on the same network. It doesn't work outside the game either. I even tried following a basic tutorial about just sending messages between computers, but I even somehow stuffed that up. I checked the ports, and tried having the computers connected through WiFi each, one WiFi/one Ethernet, and both Ethernet.
Was This Post Helpful? 0
  • +
  • -

#4 Radius Nightly  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 88
  • Joined: 07-May 15

Re: Server/Client UDP game error in code

Posted 02 November 2017 - 05:33 AM

Then first be sure they are connected properly in LAN.
From basics, check your network settings, firewall, set same Workgroup, IPs, DHCP if its a problem on router, if its on WiFi, disable AP Isolation... or simply search online how to connect two computers in LAN.
When they are connected, they usually can see each other (if they are not set on public), and you can share files between them, as any other information, as well as playing.
Until you connect your two computers in LAN properly, they are not connected, simple as that.

This post has been edited by Radius Nightly: 02 November 2017 - 05:35 AM

Was This Post Helpful? 0
  • +
  • -

#5 Shaedowhunter  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 02-November 17

Re: Server/Client UDP game error in code

Posted 02 November 2017 - 05:35 AM

Yeah, those were the first things I did. It also happened with the Uni computers, and everyone's managed to get those working so I've figured it's my code that's the issue. Just that I can't diagnose what exactly's wrong with it.
Was This Post Helpful? 0
  • +
  • -

#6 Radius Nightly  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 88
  • Joined: 07-May 15

Re: Server/Client UDP game error in code

Posted 02 November 2017 - 05:44 AM

I would first get them connected for sure, maybe there is no problem with a code, but clients computers, if they are not connected properly in LAN, i would not look into another options.
They probably manage it by IP, maybe with some server where all clients are pointed, online, or between clients, where all clients are pointed to one client, as a host, local. But if each client using localhost it means each client are connecting to itself, to be a host, and they does not trying to make connection to another device. Its like two hosts, each one for itself playing.
IDK what you made, im not into Java, just my opinion.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1