News:

Pretty crazy that we're closer to 2030, than we are 2005. Where did the time go!

Main Menu

[JAVA] Easy-To-Use Socket Interface

Started by Joe, November 06, 2005, 05:31:31 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Joe

Written by yours truely. I'm currently using this in TAHCBot v4. It handles all the streams for you and makes your life a whole hell of a lot easier.

package protocol;
/*
* TAHCBot v4
* Socket Class
* Author: Joe[e2]
*
* This is just a socket wrapper I made to make sockets easier to use
* Methods:
* - bool connect(String, int)
* - bool isConnected()
* - void sendData(String)
* - void sendData(byte[])
* - bool hasData()
* - String getData()
*/

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

import ui.*;

public class TAHCSocket {
    static Socket sck;
    static BufferedReader sck_BR;
    static OutputStream sck_OS;
    static Console ConsoleUI = new Console();
   
    public static boolean isConnected() {
    return sck.isConnected();
    }
   
    public String getData() {
    try {
    return sck_BR.readLine();
    }catch(IOException e) {
    ConsoleUI.out(4, "Unable to get data. " + e.toString());
    return "";
    }
    }

    public boolean hasData() {
    try {
    if(sck_BR.ready() == true) {
    return true;
    }else{
    return false;
    }
    }catch(IOException e) {
    ConsoleUI.out(2, "IOException thrown by sckBNET_BR.ready(): " + e.toString());
    return false;
    }
   
    }
   
    public boolean connect(String sHostname, int iPort) {
        try {
        sck = new Socket(sHostname, iPort);
        }catch(IOException e) {
        ConsoleUI.out(4, "Socket error: " + e.toString());
        return false;
        }
        makeStreams();
        return true;
    }

public static void sendData(String data) {
try {
for(int i = 0; i < data.length(); i++) {
sck_OS.write(data.charAt(i));
}
sck_OS.flush();
}catch(IOException e) {
ConsoleUI.out(2, "Error sending data. " + e.toString());
}
}

public static void sendData(byte[] data) {
try {
sck_OS.write(data);
sck_OS.flush();
}catch(IOException e) {
ConsoleUI.out(2, "Error sending data. " + e.toString());
}
}

private static void makeStreams() {
try {
sck_OS = sck.getOutputStream();
sck_BR = new BufferedReader(new InputStreamReader(sck.getInputStream()));
}catch(IOException e) {
ConsoleUI.out(2, "Could not create I/O streams. " + e.toString());
}
ConsoleUI.out(1, "Streams created.");
}
}
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


Warrior

Joe wrote something (semi)useful. *grin*
One must ask oneself: "do I will trolling to become a universal law?" And then when one realizes "yes, I do will it to be such," one feels completely justified.
-- from Groundwork for the Metaphysics of Trolling

Newby

- Newby
http://www.x86labs.org

Quote[17:32:45] * xar sets mode: -oooooooooo algorithm ban chris cipher newby stdio TehUser tnarongi|away vursed warz
[17:32:54] * xar sets mode: +o newby
[17:32:58] <xar> new rule
[17:33:02] <xar> me and newby rule all

Quote from: Rule on June 30, 2008, 01:13:20 PM
Quote from: CrAz3D on June 30, 2008, 10:38:22 AM
I'd bet that you're currently bloated like a water ballon on a hot summer's day.

That analogy doesn't even make sense.  Why would a water balloon be especially bloated on a hot summer's day? For your sake, I hope there wasn't too much logic testing on your LSAT. 

Blaze

Make a function to check if its connected!
And like a fool I believed myself, and thought I was somebody else...

Joe

Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


Blaze

Quote from: Joe[e2] on November 06, 2005, 10:50:13 PM
You do it!
I don't do Java, nor drink it, and its also YOUR class, not mine.
And like a fool I believed myself, and thought I was somebody else...

Joe

#6
It's public domain. It's not mine. I typed it, then released it. It belongs to George Bush for all I care.

EDIT -
Added bool isConnected().

EDIT -
Optimized void sendData(String).
Added void sendData(byte[]).
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


iago

Hmm, I thought Java's socket interface was really easy to use anyway..

Is it just me, or does it never both informing the program if the connection fails?

MyndFyre

Quote from: iago on November 07, 2005, 01:59:09 AM
Hmm, I thought Java's socket interface was really easy to use anyway..

Is it just me, or does it never both informing the program if the connection fails?
I don't think that last question is coherent.  :P
Quote from: Joe on January 23, 2011, 11:47:54 PM
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Quote from: Rule on May 26, 2009, 02:02:12 PMOur species really annoys me.

Joe

#9
Quote from: iago on November 07, 2005, 01:59:09 AM
Hmm, I thought Java's socket interface was really easy to use anyway..

Is it just me, or does it never both informing the program if the connection fails?

Changed void connect(String, int) to bool connect(String, int).

EDIT -
Removed Configuration object and config.* import, seeing as how its not used.

NOTE -
ConsoleUI.out(1, String) is a [DEBUG] message.
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


iago

Quote from: MyndFyrex86] link=topic=3608.msg37051#msg37051 date=1131349966]
Quote from: iago on November 07, 2005, 01:59:09 AM
Hmm, I thought Java's socket interface was really easy to use anyway..

Is it just me, or does it never both informing the program if the connection fails?
I don't think that last question is coherent.  :P
Sorry, both = bother.  Joe seemed to understand :P

Ender

#11
Few suggestions:

1. You may want a disconnect method (sorry if you have one already, and I don't see it).

2. Your data is better off being private, to adhere to concept of encapsulation. It is good that you made your makeStreams() method private, as the user/object will never be using that. Similarly, the user will never be using the first four fields. It is best to keep your data private and have a public interface instead, so that if you have to change your object's data, then these changes will be kept local, since you will already have a set-in-stone interface that other objects know about that will change/access the data.

3. There are ways of designing java programs that minimize the amount of static stuff that you need. From your code I see that parts of your GUI (ConsoleUI) and your socket interface are both static. Using the Model-View-Controller (MVC) design pattern, you can optimize a program's OO'ness. Static stuff smells like global variables, and although it is proven that a program can be written completely "staticly" (as you see in procedural programming), in Java it is best to minimize your use of static stuff. The more OOP a program is, the less work you have to do (hm, well, in theory), and the more flexible it is. This becomes much more evident in very large appplications, like the ones that require a team of programmers.

EDIT

* shrugs at posting 16 days after the last post =p *

Joe

Not a problem, bumping a post, because you contributed to it.

TAHCBot (the project this is part of) is sort of suspended right now (its stranded on my other box =p), but when I dig that out again I'll add that stuff.

Thanks Ender.
Quote from: Camel on June 09, 2009, 04:12:23 PMI'd personally do as Joe suggests

Quote from: AntiVirus on October 19, 2010, 02:36:52 PM
You might be right about that, Joe.


mynameistmp

#13
A few years ago for an IRC project I made something for initializing C sockets. I still use it sometimes. I used it in slackchat ;P I didn't want to paste all of the source on this thread, so I made this pseudo-codish C example of how it's used. If you're interested in the code I posted it at http://www.javaop.com/~tmp/isock.tar.gz.


#include "isock.h"

int main (void) {
 
        //Socket filehandle
int bnetsock;
//Declare main bnet sockaddr_in structure/socket
struct sockaddr_in bnets;
//Declare server/port
        char *server = "useast.battle.net";
        int port = 6667;

        //Create instance of sockaddr_in socket 
  create_socket (&bnets, &bnetsock, sport, sserver)
   
        //Connect the socket
    irc_connect(bnetsock, bnets)
       
        printf("TCP stream initiated on %s:%d.\n", sserver, sport);
        send(bnetsock, "\x1", 1, 0);
}

Ryan Marcus

Excuse my Java newb-ey-ness, but what characters are sent after every string, and what characters does readline look for, and are the two the same?

If I tell your socket to write out "test" will it send "test" + ASCII 13, "test" + ASCIII 10, "test" + ASCII 13 + ASCII 10, or something completely different?
Thanks, Ryan Marcus

Quote
<OG-Trust> I BET YOU GOT A CAR!
<OG-Trust> A JAPANESE CAR!
Quote
deadly: Big blue fatass to the rescue!
496620796F75722072656164696E6720746869732C20796F75722061206E6572642E00