• Welcome to Valhalla Legends Archive.
 

Bot basics (Java)

Started by mirza911, December 20, 2009, 06:26 PM

Previous topic - Next topic

Hdx

Show me your code.
If you did it correctly, you should know how to:
Create a Socket that is listening for connections
Accept incoming connections
Create a socket that connects to a remote server
Send data through a socket
Receive data through a socket
And hopefully, you've learned how to handle errors and tell when a socket is closed, could not connect, etc..

Proud host of the JBLS server www.JBLS.org.
JBLS.org Status:
JBLS/BNLS Server Status

mirza911

This is what i got so far

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

public class EchoServer
{
    public static void main(String[] args)
    {
        try
        {
            ServerSocket s = new ServerSocket(6112);
            while (true)
            {
                Socket incoming = s.accept();
                // buffer
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        incoming.getInputStream()));
                // writer
                PrintWriter out = new PrintWriter(new OutputStreamWriter(
                        incoming.getOutputStream()));

                out.println("Started - Type something to send");
                out.println("Enter \"E\" to exit.");
                out.flush();
                while (true)
                {
                    // read it in
                    String str = in.readLine();
                    if (str == null)
                    {
                        break; // client closed connection
                    }
                    else
                    {
                        // print echo back
                        out.println("Echo: " + str);
                        out.flush();
                        if (str.trim().equals("E"))
                            break;
                    }
                }
                incoming.close();
            }
        } catch (Exception e)
        {
            // handle some exceptions not sure how yet
        }
        return;
    }
}

Also i would like to know how to do that thing where u show the code in green text on posts =)

Hdx

#17
Use the [ code][ /code] (sans spaces) tag.
And a few notes:
Name your variables descriptively, save single char vars for counters, exa: sckServer or the socket, and x for for loop indexs
while(true) works, but you should NEVER have infinite loops.
Buffered readers, and writers are ok, but have you tried reading the input data yourself? because you'd have to do that for a binary protocol. Read the java docs for InputStream/OutputStream, it's simple
Make sure you understand why you used .trim() and .equals()
When dealing with single characters it's better to use constant comparisons: .charAt(0) = 'E'
And you need to learn how/why to handle exceptions, and how to deal with ones you expect (make it user friendly :P)
Also, you don't need to return from a function as the last line :P

And where is your client class?

Proud host of the JBLS server www.JBLS.org.
JBLS.org Status:
JBLS/BNLS Server Status

mirza911

Still am not sure how to use the code tag.

but here is my server

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

public class EchoServer
{
    public static void main(String[] args)
    {
        try
        {
            ServerSocket srvrSocket = new ServerSocket(4004);
            while (true)
            {
                Socket incoming = srvrSocket.accept();
                // buffer
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        incoming.getInputStream()));
                // writer
                PrintWriter out = new PrintWriter(new OutputStreamWriter(
                        incoming.getOutputStream()));

                while (true)
                {
                    // read it in
                    String str = in.readLine();
                    if (str == null)
                    {
                        break; // client closed connection
                    }
                    else
                    {
                        // print echo back
                        out.println("Echo: " + str);
                        out.flush();
                        if (str.trim().equals("BYE"))
                            break;
                    }
                }
                incoming.close();
            }
        } catch (Exception e)
        {
            System.out.println("Exception... exiting!");
            System.err.println(e);
            return;
        }
    }
}


and here is my client



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

public class EchoClient
{

    public static void main(String[] args)
    {

        String hostname = "localhost";

        if (args.length > 0)
        {
            hostname = args[0];
        }

        PrintWriter out = null;
        BufferedReader networkIn = null;
        try
        {
            Socket clientSocket = new Socket(hostname, 4004);
            networkIn = new BufferedReader(new InputStreamReader(clientSocket
                    .getInputStream()));
            BufferedReader userIn = new BufferedReader(new InputStreamReader(
                    System.in));
            out = new PrintWriter(clientSocket.getOutputStream());
            System.out.println("Connected to echo server");
            System.out.println("Started - Type something to send");
            System.out.println("Enter BYE to exit.");

            while (true)
            {
                String theLine = userIn.readLine();
                if (theLine.equals("BYE"))
                {
                    System.out.println("Exiting");
                    break;
                }
                out.println(theLine);
                out.flush();
                System.out.println(networkIn.readLine());
            }

        } // end try
        catch (IOException e)
        {
            System.out.println("IOException... exiting!");
            System.err.println(e);
            return;
        } finally
        {
            try
            {
                if (networkIn != null)
                    networkIn.close();
                if (out != null)
                    out.close();
            } catch (IOException e)
            {
                System.out.println("IOException... exiting!");
                System.err.println(e);
                return;
            }
        }
    }
}

The variables i know about. i was just kind of rushing through it =P.
what should i use instead of while(true)?
.trim to get rid of whitespaces? and .equals to check if i want to quit or not
Still no sure about the exception more advice on that would be great. how exactly i should handle them.

the return is just for me. sometimes my java programs will stick around if i dont return at the end and i will have to go into the task manager and get rid of them.


I know im still using buffers and pw's but im just taking babysteps. let me know what u think of this now and ill get started on reading the stuff without them. any tips greatly appreciated =)

Hdx

#19
Have you never used a forum before?
Just type {code}{/code} using []'s instead of {}'s (I hate not being able to not use tags :P)
But a few more note:
You should NOT need to use return, it's something else in your code thats not making it exit properly
Instead of while(true) it should be something like while(running) and set running = true, false if it needs to exit.
Also, you have 'BYE' exiting on the client, w/o sending it to the server, and you have the server terminating the connection on 'BYE' choose one or the other, not both. Just try and define a clear order of events, and responses, it should help establish a mindset of rigor protocols.
You don't really need a Finally case, you should have a generic error handler, and then specific ones for the errors you expect to happen (IO for socket errors, and Exception for generic)

Also, even though it defaults to .toString() when you print exceptions, you should still use it, just good habbits :/

Anyways, I guess you can move along to not using buffered readers/writers.

Proud host of the JBLS server www.JBLS.org.
JBLS.org Status:
JBLS/BNLS Server Status

mirza911

lol ive used forums but this is just escaping my mind.
With while running would that be the same thing? setting it to false when they type in "BYE". so it would have the same functionality?
With the BYE you want me to send it to the client and then exit?

Hdx

The infinite loop is prolly why your programs are sticking around after you want them to.
And make two commands, 1 on the server, that closes the connection. So you can handle on the client an unexpected disconnect exception, and 1 on the client that closes the connection so you can handle unexpected closured on the server.
using a var for thw while condition would make the loop exit cleanly when you want to kill the server.

Proud host of the JBLS server www.JBLS.org.
JBLS.org Status:
JBLS/BNLS Server Status