Problems with catching dataInputStream.readUTF(); - java

I'm making a Java program to make my computer a server to communicate with my smartphone over WiFi. Therefore I use the Socket class, as can be seen in the code below (based on Android-er):
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerCommunication {
#SuppressWarnings("resource")
public static void main(String[] args){
ServerSocket serverSocket = null;
Socket clientSocket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
String message = null;
try {
int portNumber = 8888;
serverSocket = new ServerSocket(portNumber);
System.out.println("Listening :" + Integer.toString(portNumber));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
clientSocket = serverSocket.accept();
dataInputStream = new DataInputStream(clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("ip: " + clientSocket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("test");
message = dataInputStream.readUTF(); // <--- PROBLEM LINE
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( clientSocket!= null){
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Everything works perfectly when the problem line (indicated with <---) is not present in the file. The message I receive is properly printed in the console. But form the moment I want to store this message in a String, I get a java.io.EOFException...
Can anyone tell me why I can print a message, but not store it as a string?
Thanks in advance!

The exception java.io.EOFException says that all the data in the stream is read, looks like you are trying to consume the data twice, one in the following statement,
System.out.println("message: " + dataInputStream.readUTF());
and the next one in,
dataInputStream.readUTF()
Either write more data from the writing side (client side) or consume once. Hope it helps.

Once you call
dataInputStream.readUTF();
it pops the string and you print that one. Then in the second call since there are no more data in outputstream the End Of File exception occurs.
You may try storing the popped string to a variable and then printing it:
String message = dataInputStream.readUTF();
System.out.println("message: " + message);

Remove your problem line
message = dataInputStream.readUTF(); // <--- PROBLEM LINE

Related

ClientSocket NOT listening

Im flabbergasted.
I took code from https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoServer.java
for the server. And
https://docs.oracle.com/javase/tutorial/networking/sockets/examples/EchoClient.java
for the Client. I made minor changes. Mostly so that there is no back and forth echoing. Rather the Server should constantly with 2 second delays send same string. But I just cant understand why the client isnt working.
It sends the Exception message:
Couldn't get I/O for the connection to 127.0.0.1
I run the server with: java 6788
and the client with: 127.0.0.1 6788
I tried other ports.
I do this in eclipse so I set the arguments in Runconfiguration before running the classes. I start the server first. I tried in terminal outside of eclipse. Nothing makes it work.
Basically, the client should connect to server and output with System.out.println() what the server in turn outputs to the client. But nothing happens.
what is wrong?
Client:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName, portNumber);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
) {
String userInput;
while (true) {
System.out.println("recieved: " + in.readLine());
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Server:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.err.println("Usage: java EchoServer <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
System.out.println(args[0]);
InetAddress add = InetAddress.getLocalHost();
System.out.println(add.getHostAddress());
try (
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream());
) {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("HELLO!");
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
You have to send the answer to the client.
Add a out.flush();
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.println("HELLO!");
out.flush();
}
As in the comment I eventually found a solution. BufferedReader.readLine() "blocked". When reading from a file it returns a line after reading up to a newline character, if I understand it correctly.
But since it was "A steady flow" from server with no newlines, it just kept "reading" and never returned a String.
I then tried using BufferedReader.read() method, that reads character by character, and returns after each char (thus never blocking). It then prints each character as it arrives, also it listens for a newline being sent from server, and once a read character equals a newline, it then prints a newline instead. Sort of emulating the "read line" behaviour I was expecting from original question.
Reading part of client:
while(true) {
character = (char) reader.read();
if(Character.isISOControl(character)) {
System.out.println();
}
else {
System.out.printf("%c", character);
}
}
Sending Part of Server:
private String message = "HELLO\n";
...
while(true) {
try {
Thread.sleep(2000);
writer.write(message);
writer.flush();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Server(Python) - Client(Java) communication using sockets

I try to send a message from server to a client, after client receives the message, it sends back a message to the server and so on. The problem is with receiving the message in python. The loop it's stuck there.
import socket
HOST = "localhost"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')
try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
print("Socket Listening")
conn, addr = s.accept()
while(True):
conn.send(bytes("Message"+"\r\n",'UTF-8'))
print("Message sent")
data = conn.recv(1024)
print(data.decode(encoding='UTF-8'))
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Main {
static Thread sent;
static Thread receive;
static Socket socket;
public static void main(String args[]){
try {
socket = new Socket("localhost",9999);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable() {
#Override
public void run() {
try {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true){
System.out.println("Trying to read...");
String in = stdIn.readLine();
System.out.println(in);
out.print("Try"+"\r\n");
System.out.println("Message sent");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The Python code is fine. The problem is that calling out.print in the Java code does not necessarily cause your message to be sent through the socket immediately. Add
out.flush();
immediately after
out.print("Try"+"\r\n");
to force the message to be sent through the socket. (flush "flushes" through the stream any data that has not yet been sent.) The Python should then be able to receive it correctly.

UDP - Java Server sends String to C++/CLI .net Client

I'm trying to send a stream of Strings from a Java server to a C++/CLI Client, but before doing that I wanted to start with the simplest case, i.e. send a single String from a Java Server to a C++/CLI client and display it.
The examples I found in the literature or in tutorials didn't work for me, knowing that the same Java Server communicated easily with another Java Client (either on the same machine or on different machines).
Without further ado, here's my Code:
the Java Server Side: SendStringToCpp.java
import java.net.*;
import java.io.*;
public class SendStringToCpp {
public static void main(String[] args) {
String message = "message"; // The String that contains the information
byte[] sentBytes = message.getBytes();
System.out.println("Message: " + message);
ServerSocket s = null;
try {
s = new ServerSocket(30011);
} catch (IOException e) {
e.printStackTrace();
}
Socket s1 = null;
try {
s1 = s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream s1out = null;
try {
s1out = s1.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream (s1out);
try {
//dos.writeUTF(message); // Sending the String
dos.write(sentBytes); // Sending the bytes
} catch (IOException e) {
e.printStackTrace();
}
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s1out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The C++ Client Side: ReceiveStringFromJava.cpp
#include "stdafx.h"
#include <exception>
using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::IO;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Creating the Socket...");
try {
//Socket^ listener = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
//Creates a UdpClient for reading incoming data.
UdpClient^ receivingUdpClient = gcnew UdpClient();
IPEndPoint^ RemoteIpEndPoint = gcnew IPEndPoint(IPAddress::Any, 30011);
//listener->Bind(RemoteIpEndPoint);
array <Byte>^ receiveBytes = receivingUdpClient->Receive(RemoteIpEndPoint); // get the Bytes array from the end poitn
String^ receivedString = Encoding::ASCII->GetString(receiveBytes); // retrieve the string from the received Bytes
Console::WriteLine("This is the message received {0}", receivedString);
// Console::WriteLine("this message was send from {0} on their ort number {1}", RemoteIpEndPoint->Address, RemoteIpEndPoint->Port);
}
catch (Exception^ e) {
Console::WriteLine("Error! ");
Console::WriteLine( e->ToString());
}
Console::ReadLine();
return 0;
}
And Here's the Exception printed on the Console:
http://i.stack.imgur.com/uTDqm.jpg
P.S. I tried to Bind the IPEndPoint to the Socket (it's commented above), but to no avail, and gave the same Error.
Socket^ listener = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
.
.
listener->Bind(RemoteIpEndPoint);
You need to use the UdpClient constructor that allows binding to a listening port.
Quoting MSDN (emphasis mine):
Initializes a new instance of the UdpClient class and binds it to the
local port number provided.
UdpClient^ receivingUdpClient = gcnew UdpClient(30011);
// specify the port both here ^^^^^ and here vvvvv
IPEndPoint^ RemoteIpEndPoint = gcnew IPEndPoint(IPAddress::Any, 30011);
array <Byte>^ receiveBytes = receivingUdpClient->Receive(RemoteIpEndPoint);

eofexception while setting up stream

I'm trying to send a string to the servlet from java program and retrieve the same string with some padding.
Here's the code i'm working on and the problem is java.io.EOFException is being thrown at the establishment of inputstream in java program.
why does the end of stream is occuring when i'm setting it up. please clarify my doubt.
Servlet program is
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProgServlet implements Servlet {
public void init(ServletConfig sc){
}
public void service (ServletRequest req,ServletResponse res)
throws ServletException, java.io.IOException
{
}
public void destroy(){
}
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
//Setting up streams
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
String p = "Server String";
//Receiving data from client and resends by padding
try {
p = (String) ois.readObject();
p = p.concat(" -sever padding");
oos.writeObject(p);
oos.flush();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
}
}
}
java program on client is
public static void main(String arg[]) throws IOException{
System.out.println("Enter a string :");
Scanner s = new Scanner(System.in);
String data = s.next();
s.close();
URL serv = null;
try {
serv = new URL("http://10.0.0.9:8080/project/projectservlet");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpURLConnection servletConnection = null;
System.out.println("establishing communication with server....");
try {
servletConnection = (HttpURLConnection) serv.openConnection();
System.out.println("connection with the server established"+servletConnection.getRequestMethod());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
servletConnection.setRequestMethod("POST");
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(""+servletConnection.getRequestMethod());
servletConnection.setDoOutput(true);
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
System.out.println("setting up streams to communicate...");
ObjectOutputStream dos = null;
ObjectInputStream dis = null;
try {
dos = new ObjectOutputStream(servletConnection.getOutputStream());
System.out.println("Streams are up and ready to go");
System.out.println("Sending data to the server...");
dos.flush();
dos.writeObject(data);
dos.flush();
System.out.println("Data sent successfullyy \n Retrieving data from server");
dis = new ObjectInputStream(servletConnection.getInputStream());
data = (String) dis.readObject();
System.out.println("Data retrieved from the server is "+data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
dos.close();
dis.close();
servletConnection.disconnect();
}
}
the output and stack trace is
Enter a string :
jaggu
establishing communication with server....
connection with the server established
GET
POST
setting up streams to communicate...
Streams are up and ready to go
Sending data to the server...
Data sent successfully
Retrieving data from server
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at ServletInvokation.main(ServletInvokation.java:57)
Exception in thread "main" java.lang.NullPointerException
at ServletInvokation.main(ServletInvokation.java:69)
In the java client, the output stream represents the request sent to the server, and the input stream represents the response retrieved from the server. When you call servletConnection.getInputStream(), you are requesting the response from the server, so it immediately sends the HTTP request to the server. But if you look at your code, at that point you have not yet written anything to the output stream, so you are actually trying to send an empty request, and that's why you are getting an EOFException.
Try doing it in two steps instead. First, get the output stream, write to it and close it. Then get the input stream and read from it.
See also this answer.
Close OutPutStream in servlet after servlet work is completed.

How can I implement a c++ socket server against a java client?

Im developing a client-server app. The client side is Java based, the server side is C++ in Windows.
Im trying to communicate them with Sockets, but im having some trouble.
I have succesfully communicated the client with a Java Server, to test if it was my client that was wrong, but its not, it seems like im not doing it right in the C++ version.
The java server goes like this:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args){
boolean again = true;
String mens;
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(12321);
System.out.println("Listening :12321");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(again){
try {
System.out.println("Waiting connection...");
socket = serverSocket.accept();
System.out.println("Connected");
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
while (again){
mens = dataInputStream.readUTF();
System.out.println("MSG: " + mens);
if (mens.compareTo("Finish")==0){
again = false;
}
}
} catch (IOException e) {
System.out.println("End of connection");
//e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
System.out.println("End of program");
}
}
The client just makes a connection and sends some messages introduced by the user.
Could you please give me a similar working server but in C++ (in Windows)?
I can't make it work by myself.
Thanx.
Your problem is that you are sending a java string which could take 1 or 2 bytes per character (see bytes of a string in java?)
You will need to send and receive in ascii bytes to make things easier, imagine data is your data string on the client side:
byte[] dataBytes = data.getBytes(Charset.forName("ASCII"));
for (int lc=0;lc < dataBytes.length ; lc++)
{
os.writeByte(dataBytes[lc]);
}
byte responseByte = 0;
char response = 0;
responseByte = is.readByte();
response = (char)responseByte;
where is and os are the client side DataInputStream and DataOutputStream respectively.
You can also sniff your tcp traffic to see what's going on :)

Categories