Valhalla Legends Forums Archive | Java Programming | Socket Recieve

AuthorMessageTime
Spilled[DW]
Hi i was seeking some help with recieving data from a Socket in Java and thought i would try here. Here is something I've wrote real fast to show you the little that i know in recieving data from the socket. So here it is:

[code]
import java.awt.*;
import java.applet.*;
import java.net.*;
import java.io.*;

public class JavaBot extends Applet
{
private PrintWriter out = null;
private BufferedReader in = null;
public void init()
{
connect();

}

public void connect()
{
Socket wSock = new Socket("63.241.83.8", 6112);
Graphics g = null;
String strData;
out = new PrintWriter(wSock.getOutputStream(),
true);
while((strData = in.readLine()) != null)
{
strData = in.read();
g.drawString("Server: " + strData, 70, 90);
}
}
}
[/code]

Some help? Im trying to get this to connect to the server i wrote in vb and on connect the vb server will send a string of "Hello" and i need the string of Hello or any other data sent put into the string variable strData. Thanks in advance guys :)
September 29, 2005, 9:43 PM
rabbit
[code]
import java.io.*;

public class clssockets extends Thread
{
public PrintWriter out;
public InputStream inp;

public clssockets()
{

}

public void run()
{
try
{
out = new PrintWriter(main.clientSocket.getOutputStream(), true);
    inp = main.clientSocket.getInputStream();
} catch(IOException e) {
System.out.println("Error: " + e);
}

    boolean c = false;
    int [] stream;
    int temp = 0;
    int i = 0;
       
    while(main.x == false)
    {
    if(main.serverSocket.isClosed() || main.clientSocket.isClosed()) main.x = true;
    stream = new int[65535];
    stream[1] = 0;
    stream[2] = 4;
    while(c == false)
    {
    try {
    int v = inp.read();
   
    if(v >= 0)
      {
      stream[i] = v;
      int top = (stream[1] + 1) * (stream[2] + 1);
      i++;
      if(i == top)
      c = true;
      } else {
      c = true;
      }
   
        if(main.serverSocket.isClosed() || main.clientSocket.isClosed())
        {
        main.x = true;
        c = true;
        }
       
    } catch(IOException e) {
    System.out.println("Error: " + e);
    }
    }
     
    c = false;
     
    parseclass p = new parseclass();
    int [] s = p.retval(stream);
        int roof = (s[1] + 1) * (s[2] + 1);
     
    for(i = 0; i < roof; i++)
    {
    out.write((char) s[i]);
    }
    }
}
}[/code]That's something I wrote sometime last year.  parseclass is pretty big, so I don't feel like posting it, but I'm sure you get the idea from this......
September 30, 2005, 1:01 AM
gameschild
This is based on the code you have, and is commented with a few suggestions and reasons.

Hope it works out!

[code]
import java.applet.Applet;
import java.io.BufferedInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class JavaBot extends Applet implements Runnable {
/*
* moved here so the thread can access it
* also, make it a ServerSocket so it can listen for connections
*/
private ServerSocket wSock = null;
/*
* there is no need to write data, so remove the printwriter
*/

public static void main(String[] args) {
JavaBot jBot = new JavaBot();
jBot.init();
}

public void init() {
listen();
}

protected void listen() {
try {
/*
* create a socket that listens on port 6112
*/
wSock = new ServerSocket(6112);
/*
* create a thread and start it, so it will wait for new connections!
*/
Thread t = new Thread(this);
t.start();
/*
* catch any errors that may occur starting it here
*/
}catch(Exception e) {
System.out.println("Error creating Socket - " + e);
return;
}
}

/*
* this is the main thread loop
*/
public void run() {
while(true) {
/*
* check the server is up, if not exit
*/
if(wSock == null) {
System.out.println("server object not created");
break;
}

System.out.println("waiting for client to connect...");

try {
/*
* here we wait for a client to connect (blocking i/o operating)
* and when one does we create a new Socket object to talk to the
* new client
*/
Socket newClient = wSock.accept();
System.out.println("a new client has connected [" + newClient + "]");

/*
* we then create a buffered input stream to read any data
*/
BufferedInputStream inData = new BufferedInputStream(newClient.getInputStream());

/*
* this will wait for the client to send data, or if they disconnect
* it will return -1
*/
int firstByte = inData.read();
if(firstByte == -1) {
System.out.println("The client closed the connection");
}else{
/*
* create a buffer to store the data. you could replace inData.available(), we add one
* because we have already read the byte in the variable firstByte
*/
byte[] data = new byte[inData.available() + 1];

/*
* 1) read first byte into buffer
* 2) read the bytes in 'data', starting array position 1, with length of 'data' into 'data'
*/
data[0] = (byte)firstByte;
inData.read(data, 1, data.length-1);
String strData = new String(data);

/*
* print the data out to the stdout
*/
System.out.println("The Client sent [" + strData + "]");

/*
* close the connection and listen for more.
* really you should have a class for handling new clients
* or some other way, so that this loop is unaffected and
* the processing is seperated
*/
newClient.close();
}
/*
* if an error occurs exit out and print the error
*/
}catch(Exception e) {
System.out.println("Error listening for and processing connections or data - " + e);
break;
}
}
}
}
[/code]
September 30, 2005, 1:16 AM
Spilled[DW]
Hrmm... i c.... Thanks for the help. After looking at that this is how I've did my coding for a client to connect to battle.net:
[code]
import java.applet.Applet;
import java.io.BufferedInputStream;
import java.net.Socket;
import javax.swing.Graphics;

public class JavaBot extends Applet
{
public static void main(String[] args) {
JavaBot jBot = new JavaBot();
jBot.init();
}

public void init()
{
attemptConnect(Graphics g);
}

/*
* this is the main thread loop
*/
public void attemptConnect(Graphics g) {
String server = "63.241.83.8";
int port = 6112;
while(true) {
try {
Socket wSock = new Socket(server, port);
/*
* we then create a buffered input stream to read any data
*/
BufferedInputStream inData = new BufferedInputStream(wSock.getInputStream());

/*
* this will wait for the client to send data, or if they disconnect
* it will return -1
*/
int firstByte = inData.read();
if(firstByte == -1)
{
g.drawString("die!", 60, 70);
}
else
{
byte[] data = new byte[inData.available() + 1];
data[0] = (byte)firstByte;
inData.read(data, 1, data.length-1);
String strData = new String(data);
wSock.close();
}
}
catch(Exception e)
{
g.drawString("Error: " + e, 100, 110);
break;
}
}
}
}
[/code]

the program gets the data from the Socket and stores the data into strData right? Thanks in advance!
September 30, 2005, 7:02 AM
gameschild
From what i've seen this will connect to a host and wait for data, which is then printed to the console and then the connection is closed and it loops around and connects again.

This means you're constantly connecting, reading, disconnecting and then doing this all over again. If this is intended thats fine but if you want to connect, and stay connected then you may wish to change the loop to read and only connect once.

[code]
import java.applet.Applet;
import java.awt.Graphics;
import java.io.BufferedInputStream;
import java.net.Socket;

public class JavaBot extends Applet {
public static void main(String[] args) {
JavaBot jBot = new JavaBot();
jBot.init();
}

public void init() {
/*
* little mistake here, not sure why ure using graphics but wont ask :)
*/
attemptConnect(new Graphics());
}

/*
* this is the main thread loop
*/
public void attemptConnect(Graphics g) {
String server = "63.241.83.8";
int port = 6112;
/*
* move the calls to create the socket out of the loop
* so we only do it once.
* we also move the buffered reader so we dont keep
* re-assigning it
*/
Socket wSock;
BufferedInputStream inData;
try {
wSock = new Socket(server, port);
System.out.println("connected to [" + wSock + "]");

/*
* we then create a buffered input stream to read any data
*/
inData = new BufferedInputStream(wSock.getInputStream());
}catch(Exception e) {
System.out.println("Error connecting to host - " + e);
return;
}

while(true) {
try {
/*
* this will wait for the client to send data, or if they disconnect
* it will return -1
*/
int firstByte = inData.read();
if(firstByte == -1) {
/*
* this 'break' will exit our read 'while(true)' loop
*/
//g.drawString("die!", 60, 70);
System.out.println("connection lost");
break;
}else{
byte[] data = new byte[inData.available() + 1];
data[0] = (byte)firstByte;
inData.read(data, 1, data.length-1);
String strData = new String(data);
// g.drawString("battle.net sent [" + strData + "]", 60, 70);
System.out.println("got: " + strData);

/*
* here we have removed the close connection, and instead wait for
* the server to close the connection.
*/
//wSock.close();
}
}
catch(Exception e) {
//g.drawString("Error: " + e, 100, 110);
System.out.println("Error: " + e);
break;
}
}
/*
* at this point the server has closed the connection
* or an error has occured and you can perform post-connection
* operations
*/
System.out.println("stopped reading");
}
}
[/code]

I use netcat (nc.exe) to test stuff like this and i advice you do the same, you can make it act like a server or client and its interactive so you can test it by just typing data. EG:
nc -l -vv -p 6112
Will listen (-l) on port 6112 (-p 6112) and be very verbose (-vv).
Depending on how your server closes the connection various exceptions will be thrown which will be reported in this code as errors.
September 30, 2005, 10:16 AM
Spilled[DW]
aww... i c Thanks for the help bro. Now on the other hand that doesn't run in a seperate thread so how would i go about sending packets if its stuck in the loop? Also i wanna create this in a JFrame, as i  am reading about them as we currently speak. Thanks in advance
September 30, 2005, 10:59 PM
gameschild
You are indeed correct, although this time i won't write the code and see how you do.

You need to either extend Thread, which you cant do because you're extending Applet, or you can implement Runnable.

[code]public class JavaBot extends Applet implements Runnable {[/code]

You would also need to create a private instance of a socket, rather than one nested in a function so the read thread can read from it and also so a write function can write to the socket.

[code]
private Socket mySock;

public void run() {
//read code goes here
}

public void write(String data) {
write(s.getBytes());
}

public void write(byte[] data) {
//write code goes here
}
[/code]
October 2, 2005, 7:23 PM

Search