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[i]= (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
cbroussard@liquiddatainc.com - 01 Dec 2005 22:35 GMT
I'd check http://java.sun.com tutorials.. they have good networking
samples. That'd probably be the easiest way to learn.
http://www.binaryfrost.com
cbroussard@liquiddatainc.com - 01 Dec 2005 22:38 GMT
here's the exact url if i managed to find for you...
http://java.sun.com/docs/books/tutorial/networking/index.html
hope that helps,
http://www.binaryfrost.com
Jean-Francois Briere - 06 Dec 2005 05:04 GMT
> 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
Phillip D Ferguson - 07 Dec 2005 14:31 GMT
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[i]= (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 : ";
}
}
}
}
========================================================
>> I cannot reply with a string...... i don't understand why? can someone
>> help?
[quoted text clipped - 30 lines]
>
> Regards
Jean-Francois Briere - 07 Dec 2005 17:55 GMT
> 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();
}
}
}
Phillip D Ferguson - 14 Dec 2005 11:41 GMT
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 :-)
>> Next is multithreading.... any tips?
>
[quoted text clipped - 64 lines]
> }
> }
Jean-Francois Briere - 15 Dec 2005 07:46 GMT
It's better to first send the size of the file.
Phillip D Ferguson - 15 Dec 2005 21:13 GMT
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
> It's better to first send the size of the file.
Jean-Francois Briere - 16 Dec 2005 06:35 GMT
> 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
Nigel Wade - 19 Dec 2005 13:01 GMT
> Thank you very much kind sir!!
>
[quoted text clipped - 22 lines]
>
> 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.

Signature
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555