readUTF() returns error after writeObject() - java

I'm setting up a new server-client system. Here from the client, an object will be sent to the server. And after receiving the object the server will send a string to the client.
Here the server reads the object successfully. But when the clients want to read the string sent by the server it throws EOFException.
client-side
public static void main(String args[]) throws IOException, EOFException {
try (Socket socket = new Socket("localhost", 1254)) {
OutputStream outputStream = socket.getOutputStream();
InputStream s1In;
DataInputStream dis;
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
s1In = socket.getInputStream();
dis = new DataInputStream(s1In);
Frame frame = new Frame();
frame.setData("test");
objectOutputStream.writeObject(frame);
String st = "";
while(dis.available() >0){
st = dis.readUTF();
}
System.out.println(st);
}
dis.close();
s1In.close();
}
}
server-side
public static void main(String args[]) throws IOException, ClassNotFoundException {
ServerSocket s = new ServerSocket(1254);
Socket socket = s.accept();
OutputStream outputStream = socket.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
//input stream
InputStream inputStream = socket.getInputStream();
DataInputStream dataInputStream = new DataInputStream(inputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Frame frame = new Frame();
frame = (Frame) objectInputStream.readObject();
String data = frame.getData();
System.out.println(data);
// Send a string!
DataOutputStream dos = new DataOutputStream (outputStream);
dos.writeUTF("Received");
dos.close();
objectOutputStream.close();
outputStream.close();
objectInputStream.close();
inputStream.close();
socket.close();
}
error at client side
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at computernetworklab.Client.main(Client.java:38)
/home/shahad/.cache/netbeans/8.2/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)

Related

Thread cannot read and write streams on the same socket at the same time?

Code with lines commented-out works, code with those lines does not.....why? and how do I fix it? (note: roughly same code running on the other end)
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream);
//ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true) {
//System.out.println( ois.readUTF());
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
Edit:
Made some code to make it clearer what I'm getting at, yes its a little messy. (regardless of there being two sockets or not it doesn't seem to work):
Server.java (main):
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(6666);
ServerSocket server2 = new ServerSocket(6667);
Socket socket = server.accept();
Socket socket1 = server2.accept();
OutputStream output = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(output);
ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream());
while (true) {
System.out.println("server reading");
System.out.println( ois.readUTF());
System.out.println("server writing");
oos.writeUTF("hey");
}
} catch (Exception e) {e.printStackTrace(); }
}
Client.java (main)
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 6666);
Socket socket1 = new Socket("127.0.0.1", 6667);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream());
while (true) {
System.out.println("client writing");
oos.writeUTF("yo");
System.out.println("client reading");
System.out.println( ois.readUTF() );
}
}
Output
Server:
server reading
Client:
client writing
client reading
.flush() your output streams. In my examples after writing on the output stream I have:
oos.flush();
I should have always flushed when I wanted to be sure the message was sent.

can i use multiple times (input/output)stream for different types of data transfer between two nodes [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
In this code I use multiple times of retrieve input-output data from two nodes. ... when I use more than two times input output stream it generated this type of error while running this code I need different input and output and that I want to store but unfortunate if I used more than three-time input/output stream it show error
public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to
client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}public class Server {
private static Socket socket;
public void connect() throws IOException{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server Started and listening to the port 25000");
socket = serverSocket.accept();
}
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
public void first() throws IOException{
connect();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Message received from client is "+number);
//Multiplying the number by 2 and forming the return message
String returnMessage;
try
{
int numberInIntFormat = Integer.parseInt(number);
int returnValue = numberInIntFormat*2;
returnMessage = String.valueOf(returnValue) + "\n";
}
catch(NumberFormatException e)
{
//Input was not a number. Sending proper message back to client.
returnMessage = "Please send a proper number\n";
}
second();
String e=br.readLine();System.out.println(e);
}
public void second() throws IOException{
//Sending the response back to the client.
String returnMessage="Second";
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(returnMessage);
System.out.println("Message sent to the client is "+returnMessage);
bw.flush();
}
public static void main(String args[]) throws IOException{
Server obj = new Server();
obj.first();
// obj.second();
}
public class client {
private static Socket socket;
//public void connect() throws UnknownHostException, IOException{
//}
public void first() throws IOException{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String number = "2";
String sendMessage = number + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);
String sendMessage1="3333";
bw.write(sendMessage1);
bw.flush();
//second();
}
public void second1() throws IOException{
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr;
isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
socket.close();
}
public static void main (String argd[]) throws IOException{
client obj1 = new client();
obj1.first();
}
-----------------------------------------
error
Message received from client is 2
Message sent to the client is Second
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
InputStream and OutputStream are intended to work with a single source and destination. Once you obtain an InputStream that reads from file/socket/whatever source you can use it for multiple consecutive reads. But once you are done reading from that source you need to invoke close() method on your stream.
Not closing your stream is classic reason for a memory leak in Java. In fact for that reason you ALWAYS expected to surround the usage of your source with try catch and always invoke close() method in finally statement. So to insure that it is always invoked. Further more, since close() method itself can cause an Exception, within final statement you need to surround it with its own try-catch. Starting from java 7 there is a new feature called "try with resources" that deals with this particular issue.
Please read about it here

Send String from server to client - save it as textfile

I know how to send a file from a server to a client but how do I send a textstring to the client where the client save the string as a file? Should I use PrintWriter for this issue?
This is the code for sending a file from server to client:
Sending files through sockets
What I want to do is to (instead of sending a file), sending a String from the server and let the client receive it and save it as a file.
public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}
static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}
static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
client();
}
}
in that case use ObjectOutputStream at server side to write String and use ObjectInputStream at client side to read String coming from server..
so your server() method will look like this..
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
OutputStream out = socket.getOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject("your string here");
oout.close();
}
and client() method will look like this..
static void client() throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
ObjectInputStream oin = new ObjectInputStream(in);
String stringFromServer = (String) oin.readObject();
FileWriter writer = new FileWriter("received.txt");
writer.write(stringFromServer);
in.close();
writer.close();
}
also throw ClassNotFoundException in main method.
public static void main(String[] args) throws IOException, ClassNotFoundException {.......}
done...

Cannot get ObjectInputStream to work

I am currently trying to get my server to create a connection with a client. I have created a thread for each connection but the server is currently not creating the Input Stream. I have tested this by printing out numbers but only 1 and 2 get printed out. Im sure this is just a small problem that im missing.
public class ObjectHandler implements Runnable{
Socket sock;
ObjectInputStream ois;
ObjectOutputStream oops;
InputStream is;
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3");
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
outputSockets.add(oops);
}
I have now removed the throws IOException and surrounded the reader with a try catch. After the client has crashed it now prints this error:
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at ThreadPool$ObjectHandler.<init>(ThreadPool.java:95)
at ThreadPool.addThread(ThreadPool.java:31)
at ObjectServerTest.go(ObjectServerTest.java:93)
at ObjectServerTest.main(ObjectServerTest.java:124)
When constructing Object streams over sockets, you always need to construct the output stream first and flush it before creating the input stream (due to how the streams are implemented).
Remove BufferedInputStream. You do not need it. It is waiting until 4K bytes are read.
Edit:
remove BufferedOutputStream too.
And make sure that you are flushing the output stream on client side.
This works for me...
ObjectHandler:
public ObjectHandler(Socket clientSocket) throws IOException {
System.out.println("1");
sock = clientSocket;
}
#Override
public void run() {
try {
is = sock.getInputStream();
System.out.println("2");
ois = new ObjectInputStream(new BufferedInputStream(is));
System.out.println("3"+ois.readFloat());
OutputStream os = sock.getOutputStream();
oops = new ObjectOutputStream(new BufferedOutputStream(os));
} catch (IOException e) {
e.printStackTrace();
}
}
Client:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket client = new Socket(InetAddress.getByName("localhost"), 8888);
OutputStream os = client.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeFloat(new Float(10.10));
oos.flush();
}

not able to transfer Image file

hi this is my client program for transfering Image , while transfering the image file it is getting corrupted , not able to open that image file , i'm not able to identify the bug , can any one help me.
DataInputStream input = new DataInputStream(s.getInputStream());
DataOutputStream output = new DataOutputStream(s.getOutputStream());
System.out.println("Writing.......");
FileInputStream fstream = new FileInputStream("Blue hills.jpg");
DataInputStream in = new DataInputStream(fstream);
byte[] buffer = new byte[1000];
int bytes = 0;
while ((bytes = fstream.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
}
in.close();
I assume that s is a Socket and you're attempting to transfer a file over the network? Here's an example of sending a file with sockets. It just sets up a server socket in a thread and connects to itself.
public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = socket.getInputStream();
FileOutputStream out = new FileOutputStream("out.jpg");
copy(in, out);
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
Socket socket = new Socket("localhost", 3434);
OutputStream out = socket.getOutputStream();
FileInputStream in = new FileInputStream("in.jpg");
copy(in, out);
out.close();
in.close();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}

Categories