Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

Network programming in Java?


ghost's Avatar
0 0

simple simple P2P network code to send one char packets to another ip of my choice. either "r" "p" "s" (rock, paper, scissors). anybody know anything about java programming and wanna help that would be great.

i am very knowledgable about java and have created some very in depth programs using advanced data structures and such but this networking thing is just getting on my nerves and i cannot find many tuts online which show in detail P2P in java. hope some1 helps me its due next week -_^.


ghost's Avatar
0 0

yeah… if you have used java before version 1.5 this will make sense, otherwise it'll take a bit more effort….

the code would be something similar to


//this is the client
Socket s = new Socket(port(as an int), IP(as a string));

BufferedWriter send = new BufferedWrite(s.getOutputStream());
BufferedReader get = new BufferedReader(s.getInputStream());

send.write("asdf");
send.flush();

String gotten = get.readLine();

okay, thats for the client…the server is similar but for its socket you use the serversocket.


ServerSocket server = new ServerSocket(port);
Socket s = s.accept();

this may not be fully sytatically correct as i am not on my own computer or have a compiler here.

http://java.sun.com/j2se/1.4.2/docs/api/

that has all the API as to how to use that stuff check for: Socket ServerSocket

you probably will need some threading to get the timing right later on, not for a R/P/S game tho. pm me if you need more help and feel free to email me your source. i've actually written a variety of these apps, including my java portScanner.

http://www.hellboundhackers.org/readarticle.php?article_id=502

that has the stuff for that and should be a very good reference for this.

–only.Samurai


ghost's Avatar
0 0

k i'll mod my code some. but there is a way to go about it without programming a server. just sending packets straight to another ip. would i just bypass the server step and just make the player continuously listen for packets?? i'm gonna send u my code in a minute. thanks for the help. :D

EDIT k i'm using TCP and trying to do it without a server. the socket constructor in java 5 calls for a InetAddress how do i construct a InetAddress just with the ip of a computer. all the tuts out there call it by getting by the host name ex. InetAddress.getByName("www.google.com"); heres the source. the places that are wrong have huge comments that say wrong wrong wrong. lol. i'm just posting so others can help k.

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class Interface extends JApplet {
    private JMenuBar menu;
    private JMenu connect, help;
    private JMenuItem changeIP, viewIP, disconnect, manual, about;
    private JButton rock, paper, scissors;
    private JLabel title;
    private JPanel top, mid, bot, buttonPanel;
    private JTextField status;
    private AnimationPanel animationPanel;
    private ActionListener buttonListener, menuListener;
    private String ip = "127.0.0.1";
    private InetAddress opponent;
    private ServerSocket myService;
    private Socket myClient, serviceSocket;
    private DataInputStream serverInput, clientInput;
    private DataOutputStream serverOutput, clientOutput;
    private String line;
    /**
     * Constructor for objects of class Interface
     */
    public Interface(){
    //------------------------------------------------
    //set up client
    //------------------------------------------------
    try {
        opponent = InetAddress.getLocalHost(); //wrong wrong wrong
        //set up on port 9999
        myClient = new Socket(opponent, 9999); //wrong wrong wrong
        //input
        clientInput = new DataInputStream(myClient.getInputStream());
        //output
        clientOutput = new DataOutputStream(myClient.getOutputStream());
    }
    catch (IOException e) {
        System.out.println(e);
    }
    //--------------------------------------------------
    //set up the game
    //--------------------------------------------------        
        class buttonListener extends JButton implements ActionListener{
            public void actionPerformed(ActionEvent e){
                JButton selected = (JButton)(e.getSource());
                if(selected.equals(rock))
                    shoot("r");
                else if(selected.equals(paper))
                    shoot("p");
                else
                    shoot("s");
           }
        }
        buttonListener = new buttonListener();
        
        class menuListener extends JMenuItem implements ActionListener{
            public void actionPerformed(ActionEvent e){
                JMenuItem selected = (JMenuItem)(e.getSource());
                if(selected.equals(changeIP))
                    ip = JOptionPane.showInputDialog("Enter New IP: ");                    
                else if(selected.equals(viewIP))
                    JOptionPane.showMessageDialog(null, ip); 
                else if(selected.equals(disconnect))
                    System.exit(0);
                else if(selected.equals(manual))
                    JOptionPane.showMessageDialog(null, "Instructions for game.");
                else
                    JOptionPane.showMessageDialog(null, "Created by Jake Helman\n Version 1.0");
            }
        }
        menuListener = new menuListener();
        
        animationPanel = new AnimationPanel();
        
        top = new JPanel();
        title = new JLabel("Rock-Paper-Scissors");
        top.add(title, BorderLayout.CENTER);
        
        bot = new JPanel();
        rock = new JButton("Rock!");
        rock.addActionListener(buttonListener);
        paper = new JButton("Paper!");
        paper.addActionListener(buttonListener);
        scissors = new JButton("Scissors!");
        scissors.addActionListener(buttonListener);
        buttonPanel = new JPanel();
        buttonPanel.add(rock, BorderLayout.WEST);
        buttonPanel.add(paper, BorderLayout.CENTER);
        buttonPanel.add(scissors, BorderLayout.EAST);
        status = new JTextField("You are playing the AI.");
        status.setEditable(false);
        bot.add(buttonPanel, BorderLayout.WEST);
        bot.add(status, BorderLayout.EAST);
        
        menu = new JMenuBar();
        setJMenuBar(menu);
        connect = new JMenu("Connection");
        changeIP = new JMenuItem("Change IP");
        changeIP.addActionListener(menuListener);
        viewIP = new JMenuItem("View IP");
        viewIP.addActionListener(menuListener);
        disconnect = new JMenuItem("Disconnect");
        disconnect.addActionListener(menuListener);
        connect.add(changeIP);
        connect.add(viewIP);
        connect.add(disconnect);
        help = new JMenu("Help");
        manual = new JMenuItem("Manual");
        manual.addActionListener(menuListener);
        about = new JMenuItem("About RPS");
        about.addActionListener(menuListener);
        help.add(manual);
        help.add(about);
        menu.add(connect);
        menu.add(help);
        
        Container c = getContentPane();
        c.setLayout(new GridLayout(4,1));
        c.add(new JLabel(""));
        c.add(top);
        c.add(animationPanel);
        c.add(bot);
    }
    
    public void shoot(String s){
        if(s.equals("r"))
        {
        //send output of "r"
        try{
        clientOutput.writeBytes("r");
        clientOutput.flush();
        }
        catch(IOException e){
            System.out.println(e);
        }
        //wait for input
        String temp = null;
        while(temp==null){
            try{
            temp=clientInput.readLine();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }
        //then show moves
        if(temp.equals("r")){
            title.setText("DRAW!");
            animationPanel.p2.setIcon(animationPanel.rock);
            animationPanel.p1.setIcon(animationPanel.rock);
        }
        else if(temp.equals("p")){
            title.setText("OPPONENT WINS!");
            animationPanel.p2.setIcon(animationPanel.paper);
            animationPanel.p1.setIcon(animationPanel.rock);
        }
        else{
            title.setText("YOU WIN!");
            animationPanel.p2.setIcon(animationPanel.scissors);
            animationPanel.p1.setIcon(animationPanel.rock);
        }
        }
        else if(s.equals("p"))
        {
        //send output of "p"
        try{
        clientOutput.writeBytes("p");
        clientOutput.flush();
        }
        catch(IOException e){
            System.out.println(e);
        }
        //wait for input
        String temp = null;
        while(temp==null){
            try{
            temp=clientInput.readLine();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }
        //then show moves
        if(temp.equals("r")){
            title.setText("YOU WIN!");
            animationPanel.p2.setIcon(animationPanel.rock);
            animationPanel.p1.setIcon(animationPanel.paper);
        }
        else if(temp.equals("p")){
            title.setText("DRAW!");
            animationPanel.p1.setIcon(animationPanel.paper);
            animationPanel.p1.setIcon(animationPanel.paper);
        }
        else{
            title.setText("OPPONENT WINS!");
            animationPanel.p2.setIcon(animationPanel.scissors);
            animationPanel.p1.setIcon(animationPanel.paper);
        }
        }
        else
        {
        //send output of "s"
        try{
        clientOutput.writeBytes("s");
        clientOutput.flush();
        }
        catch(IOException e){
            System.out.println(e);
        }
        //wait for input
        String temp = null;
        while(temp==null){
            try{
            temp=clientInput.readLine();
            }
            catch(IOException e){
                System.out.println(e);
            }
        }
        //then show moves
        if(temp.equals("r")){
            title.setText("OPPONENT WINS!");
            animationPanel.p2.setIcon(animationPanel.rock);
            animationPanel.p1.setIcon(animationPanel.scissors);
        }
        else if(temp.equals("p")){
            title.setText("YOU WIN!");
            animationPanel.p2.setIcon(animationPanel.paper);
            animationPanel.p1.setIcon(animationPanel.scissors);
        }
        else{
            title.setText("DRAW!");
            animationPanel.p2.setIcon(animationPanel.scissors);
            animationPanel.p1.setIcon(animationPanel.scissors);
        } 
        }
    }
                
        
    /**
     * main method, application starts here.
     *
     * @param args execution arguments
     */
    public static void main(String[] args) {
        JFrame f = new JFrame("Rock-Paper-Scissors");
        Dimension d = new Dimension(415,300);
        f.setSize(d);
        Interface i = new Interface();
        i.init();
        i.start();
        f.add(i);
        f.setVisible(true);
    }
}```

k so theres a whole nother class called AnimationPanel but it has nothing to do with the networking part. hope some1 can help with this.
*Remember*
1. P2P = NO SERVER!
2. Direct Connection to a server IP using InetAddress or some other way.
3. Should i just use User Datagram Protocol(UDP) and will some1 help me thru it?

ghost's Avatar
0 0

okay, well you can do it without a "server," but one (and if you want p2p) both will need a ServerSocket object. That's just the way it works. Another issue i think may be that you're trying to use it in an Applet….not really sure you can do that. I think it will have Security issues on it. I'll take a closer look at your code. PM me again and let me know how i can get ALL the source from you so I can get a clean compile and try it out on my computer.


ghost's Avatar
0 0

k so they both need serversockets. i got some resources on P2P and will be trying them shortly. secondly, i'm not worried about security issues cuz this is just a quick class project i want an A on. and i can send u the files in a zip folder thru ur email. k thx


ghost's Avatar
0 0

okay, well you can do it without a "server," but one (and if you want p2p) both will need a ServerSocket object. That's just the way it works. Another issue i think may be that you're trying to use it in an Applet….not really sure you can do that. I think it will have Security issues on it. I'll take a closer look at your code. PM me again and let me know how i can get ALL the source from you so I can get a clean compile and try it out on my computer.


ghost's Avatar
0 0

wow, not really sure how that double post happened. check my profile and use aim and ill get the file from you.


ghost's Avatar
0 0

k i sent the code to ur gmail account. as the message says i read the section in "killer game programming in java" about p2p networking using a multicast address. and i implemented it. haven't tested it yet but will in the next hour if it works then WOOT! but other wise i hope you know about multicasting.:D


ghost's Avatar
0 0

alright mate. ill take a look at it asap. im at work right now so it wont be for a bit…


ghost's Avatar
0 0

don't worry about it. i'm just glad some1's willing to help. thx. and i'm pretty sure its not workin lo0ol