simple code advice for Client server array transfer

  • Thread starter Phillip D Ferguson
  • Start date
P

Phillip D Ferguson

Hello,

i'm beginning to get familiar with the network side of java, and as a quick
test platform for a project i wanted to send an array of bytes from the
client to a server. The server then responds with a string to say that the
array has been received correctly.
My main problem is with what inputstream to attached to the socket. I'm
finding it difficult to understand exactly what each read() command is
capable of.
I am able to send the array across with out too much bother. I do appreciate
my code is very basic, and probably not good, so any advice to change it
would be great.
I cannot reply with a string...... i don't understand why? can someone help?
At the moment the client code hangs on the readline()

The client code :
=============================================================================
public static void main(String argv[]) throws Exception
{

String response;
byte[] testArr = new byte[8];

for (int i=0; i<8;i++)
{
testArr= (byte)(i+1);
}

for (int j=0; j<8;j++)
{
System.out.print(testArr[j]);
}
// testing byte array contents

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket(hostname and port number);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));


outToServer.write(testArr,0,8); // i realise this is not good so any
help here would be grand!

System.out.println(testArr);

response = inFromServer.readLine(); // hangs on this line

System.out.println("Server says:" + response);

clientSocket.close();

}
}

==============================================================================

Server code:

==============================================================================

public static void main(String argv[]) throws Exception
{

String responsetoClient;
int byteread;
byte[] RtestArr = new byte[8];

ServerSocket welcomeSocket = new ServerSocket(6789);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

DataInputStream inFromClient =
new DataInputStream(new
DataInputStream(connectionSocket.getInputStream()));


DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

byteread = inFromClient.read(RtestArr,0,8);

for (int j=0; j<8;j++)
{
System.out.print(RtestArr[j]);
}

if (byteread == 8) //
{
responsetoClient = "Array confirmed";
outToClient.writeBytes(responsetoClient);
}


}
}

}


====================================================================================

i'm at a loss as to why this isn't work.... any suggestions and criticisms?
I need to learn....

cheers

Phill
 
J

Jean-Francois Briere

I cannot reply with a string...... i don't understand why? can someone help?
At the moment the client code hangs on the readline()

The reason is that readLine() will read characters up to the end of
line character.
So simply do the following in the Server code:
responsetoClient = "Array confirmed\n";

Also note that a string have to be encoded into bytes before outputed
by one side and decoded into a string after read the bytes in the other
side. So you have to use the same charset in both sides.
If you do not specify any charset, the JVM default charset will be
used.
All is fine when you test cient and server on the same machine (or
machines with the same locale).
If you want to be allways sure, use the same charset in both sides:

Client:

BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream(), "ISO-8859-1"));

Server:

outToClient.write(responsetoClient.getBytes("ISO-8859-1"));

In general your code seems ok to me.
But it is a good idea to google on some java net tutorials / samples
and
more importantly to continue to practice.
Good work!

Regards
 
P

Phillip D Ferguson

Thank jean, you have confirmed what i thought anyway.
I took sometime and went through some books and tutorials. Its the simple
things like the the end of line character that i missed.

I have left the exception handling till later just because it clouds the key
parts.

Next is multithreading.... any tips?


Final code is...
=======================================
Client
=======================================

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

class TCPClient
{

public static void main(String argv[]) throws Exception
{
String serverResp;
byte[] testArr = new byte[8];

for (int i=0; i<8;i++)
{
testArr= (byte)(i+5);
}

for (int j=0; j<8;j++)
{
System.out.print(testArr[j]+", ");
}
System.out.println("\n");
// array ok

Socket clientSocket = new Socket(address, port);

OutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));


outToServer.write(testArr);
outToServer.flush();


serverResp = inFromServer.readLine();
System.out.println("Server says - " + serverResp);

inFromServer.close();
outToServer.close();
clientSocket.close();

}
}

====================================================
================================================
Server
==============================================

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

class TCPServer {

public static void main(String argv[]) throws Exception
{

String responsetoClient = "Array confirmed : ";
int byteread;
byte[] RtestArr = new byte[8];

ServerSocket welcomeSocket = new ServerSocket(port);

while(true) {

Socket connectionSocket = welcomeSocket.accept();

InputStream inFromClient =
new DataInputStream(connectionSocket.getInputStream());

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

byteread = inFromClient.read(RtestArr);

for (int j=0; j<byteread;j++)
{
System.out.print(RtestArr[j]+",");
responsetoClient= responsetoClient + RtestArr[j]+",";
}

System.out.println("last value is: " + byteread);

if (byteread == 8)
{

outToClient.writeBytes(responsetoClient + '\n');
outToClient.flush();
responsetoClient = "Array confirmed : ";
}
}
}
}

========================================================
 
J

Jean-Francois Briere

Next is multithreading.... any tips?

I suppose you mean multithreading in the context of the TCPServer,
right?

class TCPServer
{
public static void main(String[] args) throws Exception
{
String responsetoClient = "Array confirmed : ";
int byteread;
byte[] RtestArr = new byte[8];

ServerSocket welcomeSocket = new ServerSocket(port);

while (true)
{
Socket connectionSocket = welcomeSocket.accept();

TCPServerThread tcpSrvr = new
TCPServerThread(connectionSocket);
tcpSrvr.start();
}
}
}

class TCPServerThread extends Thread
{
private Socket connectionSocket;

TCPServerThread(Socket connectionSocket)
{
this.connectionSocket = connectionSocket;
}

public void run()
{
try
{
InputStream inFromClient =
new DataInputStream(connectionSocket.getInputStream());

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

byteread = inFromClient.read(RtestArr);

for (int j=0; j<byteread;j++)
{
System.out.print(RtestArr[j]+",");
responsetoClient= responsetoClient + RtestArr[j]+",";
}

System.out.println("last value is: " + byteread);

if (byteread == 8)
{
outToClient.writeBytes(responsetoClient + '\n');
outToClient.flush();
responsetoClient = "Array confirmed : ";
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
 
P

Phillip D Ferguson

Thank you very much kind sir!!

I am now experimenting with transfering files and the requirements to do so.

How i am having problems on the server side yet again, with what appears to
be blocking.

byte[] buffer = new byte[8192];
int numbread;

while((numbread= dataInput.read(buffer) >=0 )
{
out.write(buffer, 0, numbread);
System.out.println("Receiving..." + numbread);
}
System.out.println(numbread);
System.out.println("while loop completed");

When i read this file it doesn't complete the last loop? The last segment of
data is read, and written correctly, so the file is intact and usable,
however it appears its is trying to read from an empty source. Should i be
sending the file size first? Or is there away i don't have to? I believe
when you read and get to end of file the read operation should return a -1.
It's not happening in this case...why?

Thanks :)


Jean-Francois Briere said:
Next is multithreading.... any tips?

I suppose you mean multithreading in the context of the TCPServer,
right?

class TCPServer
{
public static void main(String[] args) throws Exception
{
String responsetoClient = "Array confirmed : ";
int byteread;
byte[] RtestArr = new byte[8];

ServerSocket welcomeSocket = new ServerSocket(port);

while (true)
{
Socket connectionSocket = welcomeSocket.accept();

TCPServerThread tcpSrvr = new
TCPServerThread(connectionSocket);
tcpSrvr.start();
}
}
}

class TCPServerThread extends Thread
{
private Socket connectionSocket;

TCPServerThread(Socket connectionSocket)
{
this.connectionSocket = connectionSocket;
}

public void run()
{
try
{
InputStream inFromClient =
new DataInputStream(connectionSocket.getInputStream());

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

byteread = inFromClient.read(RtestArr);

for (int j=0; j<byteread;j++)
{
System.out.print(RtestArr[j]+",");
responsetoClient= responsetoClient + RtestArr[j]+",";
}

System.out.println("last value is: " + byteread);

if (byteread == 8)
{
outToClient.writeBytes(responsetoClient + '\n');
outToClient.flush();
responsetoClient = "Array confirmed : ";
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
 
P

Phillip D Ferguson

Haha short and sweet, thank you very much once again.

I promise to let you see the fruits of my labour once i'm finished if your
interested!

Kind regards

Phill
 
J

Jean-Francois Briere

I promise to let you see the fruits of my labour once i'm finished if your
interested!

Nice! I'm waiting impatiently :)

Jean-Francois
 
N

Nigel Wade

Phillip said:
Thank you very much kind sir!!

I am now experimenting with transfering files and the requirements to do so.

How i am having problems on the server side yet again, with what appears to
be blocking.

byte[] buffer = new byte[8192];
int numbread;

while((numbread= dataInput.read(buffer) >=0 )
{
out.write(buffer, 0, numbread);
System.out.println("Receiving..." + numbread);
}
System.out.println(numbread);
System.out.println("while loop completed");

When i read this file it doesn't complete the last loop? The last segment of
data is read, and written correctly, so the file is intact and usable,
however it appears its is trying to read from an empty source. Should i be
sending the file size first? Or is there away i don't have to? I believe
when you read and get to end of file the read operation should return a -1.
It's not happening in this case...why?

Thanks :)

read() returns -1 when the end of stream is reached. For an end of stream to be
signalled the stream needs to be closed by the sending end. Otherwise the
reader has no way of knowing if the data stream is complete, or has just
temporarily dried up due to network saturation or some problem at the sending
end.

If you need to be able to read the contents and know when the transfer has
completed whilst maintaining an open socket, then yes, you do need to send the
file size first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top