Author Topic: [JAVA] Easy-To-Use Socket Interface  (Read 9695 times)

0 Members and 1 Guest are viewing this topic.

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
[JAVA] Easy-To-Use Socket Interface
« on: November 06, 2005, 05:31:31 pm »
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.

Code: [Select]
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.");
}
}
« Last Edit: November 07, 2005, 07:49:55 am by Joe[e2] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Warrior

  • supreme mac daddy of trolls
  • Hero Member
  • *****
  • Posts: 7503
  • One for a Dime two for a Quarter!
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #1 on: November 06, 2005, 05:37:02 pm »
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

Offline Newby

  • Moderator
  • Hero Member
  • *****
  • Posts: 10877
  • Thrash!
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #2 on: November 06, 2005, 06:51:43 pm »
Warrior, you read my mind. B)
- 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

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. 

Offline Blaze

  • x86
  • Hero Member
  • *****
  • Posts: 7136
  • Canadian
    • View Profile
    • Maide
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #3 on: November 06, 2005, 10:27:43 pm »
Make a function to check if its connected!
And like a fool I believed myself, and thought I was somebody else...

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #4 on: November 06, 2005, 10:50:13 pm »
You do it!
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Blaze

  • x86
  • Hero Member
  • *****
  • Posts: 7136
  • Canadian
    • View Profile
    • Maide
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #5 on: November 06, 2005, 10:53:00 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...

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #6 on: November 06, 2005, 10:59:54 pm »
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[]).
« Last Edit: November 06, 2005, 11:07:23 pm by Joe[e2] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #7 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?

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #8 on: November 07, 2005, 02:52:46 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
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #9 on: November 07, 2005, 07:48:25 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.
« Last Edit: November 07, 2005, 07:50:51 am by Joe[e2] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #10 on: November 07, 2005, 08:41:47 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

Offline Ender

  • x86
  • Hero Member
  • *****
  • Posts: 2390
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #11 on: November 23, 2005, 05:56:28 pm »
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 *
« Last Edit: November 23, 2005, 07:11:54 pm by Ender »

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #12 on: November 23, 2005, 10:44:28 pm »
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.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline mynameistmp

  • Full Member
  • ***
  • Posts: 111
  • Hi! I'm new here!
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #13 on: November 24, 2005, 03:16:51 am »
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.

Code: [Select]
#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);
}
« Last Edit: November 24, 2005, 03:23:50 am by mynameistmp »

Offline Ryan Marcus

  • Cross Platform.
  • Full Member
  • ***
  • Posts: 170
  • I'm Bono.
    • View Profile
    • My Blog
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #14 on: November 25, 2005, 11:23:36 am »
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

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #15 on: November 25, 2005, 04:52:52 pm »
If you tell the socket to write "test", it will send "test", nothing more, nothing less.

I'm not really sure how buffered input streams (or whatever I'm using =p) work, but I guess each time it recieves a TCP packet, it adds that packet as a new thing on the buffer, and when you ask for something from the buffer, it returns the first thing and then bumps everything up a notch.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #16 on: January 30, 2007, 12:46:21 am »
Sorry to bump this, but I found some new use to it. After going through a semester of Java programming, I've decided to fix the way I did some formatting and whatnot, and I made it more generic (it doesn't use my console class, but rather uses System.err for what's necessary).

EDIT -
Whoops -- didn't review it carefully enough. I just remembered that I learned what staticness was in class, and when I wrote this, I was just trying to get around it. Fixed.

Code: [Select]
package networking;

/*
 * Author: Joe[x86]
 *
 * 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.*;

public class SocketWrapper
{
    private Socket sck;
    private BufferedReader sck_BR;
    private OutputStream sck_OS;
   
    public SocketWrapper()
    {
    }
   
    public SocketWrapper(Socket socket)
    {
    this.sck = socket;
    makeStreams();
    }
   
    public boolean isConnected()
    {
    return sck.isConnected();
    }
   
    public String getData() {
    try
    {
    return sck_BR.readLine();
    }
    catch(IOException e)
    {
    System.err.println("Socket threw IOException in getData():\n" + e.toString());
    return "";
    }
    }

    public boolean hasData()
    {
    try
    {
    if(sck_BR.ready() == true)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    catch(IOException e)
    {
    System.err.println("Socket threw IOException in hasData():\n" + e.toString());
    return false;
    }
   
    }
   
    public boolean connect(String hostname, int port)
    {
        try {
        sck = new Socket(hostname, port);
        }
        catch(IOException e)
        {
        System.err.println("Socket threw IOException in connect():\n" + e.toString());
    return false;
        }
        return makeStreams(); // this will return true if makeStreams() works
    }

public 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)
{
System.err.println("Socket threw IOException in sendData():\n" + e.toString());
}
}

public void sendData(byte[] data)
{
try
{
sck_OS.write(data);
sck_OS.flush();
}
catch(IOException e)
{
System.err.println("Socket threw IOException in sendData():\n" + e.toString());
   
}
}

private boolean makeStreams()
{
try
{
sck_OS = sck.getOutputStream();
sck_BR = new BufferedReader(new InputStreamReader(sck.getInputStream()));
}
catch(IOException e)
{
System.err.println("Socket threw IOException in makeStreams():\n" + e.toString());
try
{
sck.close();
}
catch(IOException ex)
{
// who cares? If we had an exception, it's closed anyhow. :)
}
return false;
}
return true;
}
}
« Last Edit: January 30, 2007, 01:10:11 am by Joe[x86] »
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline AntiVirus

  • Legendary
  • x86
  • Hero Member
  • *****
  • Posts: 2521
  • Best
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #17 on: January 31, 2007, 11:16:41 am »
Code: [Select]
   
public SocketWrapper()
{
}

What is the point of that?
The once grove of splendor,
Aforetime crowned by lilac and lily,
Lay now forevermore slender;
And all winds that liven
Silhouette a lone existence;
A leafless oak grasping at eternity.


"They say that I must learn to kill before I can feel safe, but I rather kill myself then turn into their slave."
- The Rasmus

Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #18 on: January 31, 2007, 11:41:32 am »
What is the point of that?

It's an override of the constructor so you don't have to provide parameters to create a 'SocketWrapper' object.  I'm not sure it makes sense considering the other constructor calls private methods, though...

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #19 on: January 31, 2007, 11:43:39 am »
Code: [Select]
   
public SocketWrapper()
{
}

What is the point of that?

The connect(String, int) method creates a new Socket object.  Creating a SocketWrapper instance with a Socket parameter does not require connect to be called; creating one without a parameter requires connect to be called.

If that constructor wasn't there, he couldn't create a SocketWrapper without a socket parameter.

I'm not sure it makes sense considering the other constructor calls private methods, though...
The connect method calls the private method you're referring to.
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #20 on: January 31, 2007, 01:33:03 pm »
The connect method calls the private method you're referring to.

Missed that.  Unfortunately, I don't have the patience to sift through Joe's code. :(

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #21 on: January 31, 2007, 10:56:31 pm »
The connect method calls the private method you're referring to.

Missed that.  Unfortunately, I don't have the patience to sift through Joe's code. :(

I'm not sure if you were trying to insult my code or your patience by saying that, but if you ask me, my code is just about as readable as JavaOp2, which is pretty decent.

And yeah, MyndFyre is correct.. originally I didn't have any constructor at all, but now that I allowed it to be constructed with a Socket object passed, I needed to manually put a no-args constructor in there. When you don't have any constructor at all, Java automagically gives it a no-args constructor.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #22 on: January 31, 2007, 11:11:14 pm »
I'm not sure if you were trying to insult my code or your patience by saying that, but if you ask me, my code is just about as readable as JavaOp2, which is pretty decent.

It'd be obvious if I was trying to insult your code.  I'm not trying to insult it; I'm merely saying I don't have the patience to read it.

Offline warz

  • Hero Member
  • *****
  • Posts: 1134
    • View Profile
    • chyea.org
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #23 on: January 31, 2007, 11:59:21 pm »
If I were wanting to read it, i'd probably drop it also. Nothing looks worse to me than code designating an entire line to a single opening french bracket ({).
« Last Edit: February 01, 2007, 12:00:53 am by warz »
http://www.chyea.org/ - web based markup debugger

Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #24 on: February 01, 2007, 12:42:18 am »
If I were wanting to read it, i'd probably drop it also. Nothing looks worse to me than code designating an entire line to a single opening french bracket ({).

I prefer adding curly brackets (I prefer that name for them :P) after statements as well.  Since it's a completely subjective decision, though, I don't think it really matters which way you prefer...

Offline Joe

  • B&
  • Moderator
  • Hero Member
  • *****
  • Posts: 10319
  • In Soviet Russia, text read you!
    • View Profile
    • Github
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #25 on: February 01, 2007, 05:26:55 pm »
I have an ungodly huge resolution, and I don't like code that looks clumped together. The brainchild of these two factors is the braces getting their line.

And what's the real name for them? To me, ( ) has always been parenthesis, [ ] are brackets, and { } are braces.
I'd personally do as Joe suggests

You might be right about that, Joe.


Offline Sidoh

  • x86
  • Hero Member
  • *****
  • Posts: 17634
  • MHNATY ~~~~~
    • View Profile
    • sidoh
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #26 on: February 01, 2007, 08:21:25 pm »
I have an ungodly huge resolution, and I don't like code that looks clumped together. The brainchild of these two factors is the braces getting their line.

And what's the real name for them? To me, ( ) has always been parenthesis, [ ] are brackets, and { } are braces.

Every CS professor here refers to them as "curly brackets."  I've never heard them called "French Brackets."

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #27 on: February 01, 2007, 09:18:15 pm »
I have an ungodly huge resolution, and I don't like code that looks clumped together. The brainchild of these two factors is the braces getting their line.

And what's the real name for them? To me, ( ) has always been parenthesis, [ ] are brackets, and { } are braces.
Those are the names I've used, except () are parentheses, and one is a parenthesis.
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.

Offline rabbit

  • x86
  • Hero Member
  • *****
  • Posts: 8092
  • I speak for the entire clan (except Joe)
    • View Profile
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #28 on: February 02, 2007, 12:21:54 pm »
I have an ungodly huge resolution, and I don't like code that looks clumped together. The brainchild of these two factors is the braces getting their line.

And what's the real name for them? To me, ( ) has always been parenthesis, [ ] are brackets, and { } are braces.

Every CS professor here refers to them as "curly brackets."  I've never heard them called "French Brackets."
Ditto!

Offline iago

  • Leader
  • Administrator
  • Hero Member
  • *****
  • Posts: 17914
  • Fnord.
    • View Profile
    • SkullSecurity
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #29 on: February 03, 2007, 12:43:55 pm »
Yeah, they're generally called curly brackets or braces here, usually braces. 

And I greatly prefer putting the opening brace on its own line.  I find it makes it easier to match up braces.  Also, it keeps code more spaced out which makes it look cleaner.  From marking assignments, I can tell you that I, as a marker, greatly prefer it on the next line. 

One of my profs was telling me that the on-the-same-line convention was created because of text-books, which have limited space.  In the olden days (think Pascal), it had to be on the next line. 

But you're right, it's completely subjective.  Those are just my opinions.  Of course, anybody who doesn't agree with me is very much wrong (kidding, of course :P)

Offline MyndFyre

  • Boticulator Extraordinaire
  • x86
  • Hero Member
  • *****
  • Posts: 4540
  • The wait is over.
    • View Profile
    • JinxBot :: the evolution in boticulation
Re: [JAVA] Easy-To-Use Socket Interface
« Reply #30 on: February 07, 2007, 10:17:59 pm »
One of my profs was telling me that the on-the-same-line convention was created because of text-books, which have limited space.  In the olden days (think Pascal), it had to be on the next line. 
I thought Pascal used things like "begin" and "end" to delimit code blocks.
I have a programming folder, and I have nothing of value there

Running with Code has a new home!

Our species really annoys me.