Read continuously? - java

I'm working on senior project and I'm trying to use this code to read from TCP socket but it reads from the socket once a time,but I need a continuous readings
Any hints
Thanks in advance!
This is the code:
class ClientAsyncTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String result = null;
try {
Socket socket = new Socket(params[0],
Integer.parseInt(params[1]));
InputStream is = socket.getInputStream();
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
out.println(params[2]);
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
//Close the client socket
socket.close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

Maybe you can use a loop for forever cycle? before you close socket with method
socket.close()
Because in official documentation:
Java doc
Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound).

Related

InputStreamReader readLine method returns wrong String

I'm trying to send a string from my java server to an android client over a socket. Instead of showing the correct String which would be "OK" the read method of the InputStreamReader returns
"��OK".
The code of the server looks like this:
public void run() {
try {
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeUTF("OK");
dOut.flush();
dOut.close();
socket.close();
System.out.println("Disconnected from client number: " + id);
} catch (IOException ex) {
Logger.getLogger(ThreadImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
And the code of the client looks like this:
public void run() {
try {
Socket socket = null;
try {
socket = new Socket("10.0.2.2", 1978);
} catch (IOException e) {
e.printStackTrace();
}
String serverRes = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ServerRes = reader.readLine();
System.out.println(ServerRes);
reader.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You should be using a DataInputStream instead of an InputStreamReader. This is the source of your problem
InputStreamReader reader = new DataInputStream(socket.getInputStream()));
String inStr = reader.readUTF();

Socket connection using BufferedReader / BufferedWriter

My server is not sending a response with BufferedWriter out to the client. It seems as if the code stops at int amountOfNumbersToBeGenerated = Integer.parseInt(bufferedReader.readLine()); I believe the bufferedreader.readline() call on the client side is causing and issue and blocking the connection in some sense.
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
public class ThreadedConnection implements Runnable {
private Socket connection;
private InputStream in;
private OutputStream out;
public ThreadedConnection(Socket connection) {
this.connection = connection;
try {
this.in = this.connection.getInputStream();
this.out = this.connection.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(out));
try {
String lotteryType = bufferedReader.readLine(); //reads first line of input stream
int amountOfNumbersToBeGenerated = Integer.parseInt(bufferedReader.readLine());
System.out.println("3"+amountOfNumbersToBeGenerated);
switch (lotteryType) {
case "LuckyForLife":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 48, 18, bufferedWriter);
break;
case "MegaMillions":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 70, 25, bufferedWriter);
break;
case "PowerBall":
generateLotteryNumbers(amountOfNumbersToBeGenerated, 69, 26, bufferedWriter);
break;
default:
break;
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
connection.close();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void generateLotteryNumbers(int amountOfNumbersToBeGenerated, int upperLimitOfGeneratedNumbers, int upperLimitOfExtraNumber, BufferedWriter bufferedWriter){
RandomNumberGenerator randomNumbers = new RandomNumberGenerator(amountOfNumbersToBeGenerated,upperLimitOfGeneratedNumbers);
RandomNumberGenerator extraNumber = new RandomNumberGenerator(1,upperLimitOfExtraNumber);
ArrayList randomNumbersArrayList = randomNumbers.NumberGenerator();
ArrayList extraNumberArrayList = extraNumber.NumberGenerator();
String randomNumbersString = randomNumbersArrayList.toString();
randomNumbersString = randomNumbersString.substring(1, randomNumbersString.length()-1);
String extraNumberString = extraNumberArrayList.toString();
extraNumberString = extraNumberString.substring(1, extraNumberString.length()-1);
try {
bufferedWriter.write(randomNumbersString);
bufferedWriter.newLine();
bufferedWriter.write(extraNumberString);
bufferedWriter.newLine();
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
// System.out.println(randomNumbersString);
// System.out.println(extraNumberString);
}
}
Here is the code for the client side. I think the first String gerneretedNumber = bufferedReader.readLine(); is causing the issue. Almost as if it is called to read when there is nothing being written out from the server and then messing with the server side read. If I block both of the readline() calls the code on the server then works and I can get something to print out on console.
static void runClient(){
OutputStream outputStream;
InputStream inputStream;
Socket client;
BufferedWriter bufferedWriter;
BufferedReader bufferedReader;
try {
System.out.println("Creating client socket ");
client = new Socket("127.0.0.1", 5000);
outputStream = client.getOutputStream();
inputStream = client.getInputStream();
bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream));
//bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));
bufferedWriter.write("LuckyForLife");
bufferedWriter.newLine();
bufferedWriter.write("5");
bufferedWriter.flush();
String generetedNumber = bufferedReader.readLine();
String extraNumber = bufferedReader.readLine();
System.out.println(gerneretedNumber);
System.out.println(extraNumber);
System.out.println("Guess its null");
bufferedReader.close();
bufferedWriter.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If anymore information is needed I am happy to post it.
your client never sends the 2nd newline.
Given your protocol, client doesn't half close (output close) so the server cannot either detect end of stream.
BTW, try to close streams (tcp FIN) before close socket (tcp RST); it's more "ethical" ! Kidding aside, the tcp rst is a kill, and pending bytes might not be flushed out (although you have plenty of flushes here, it's just good practice).

How to let a server receive more than a single message from clients?

I want to have a Server that is running and receives messages from Clients such as another Java Applications. I am doing this via BufferedReader with an InputStream and as long as i do it a single time it works as expected. The message gets processed by the method and writes the Test Message of the received message on the screen, but if i let it run in a while loop it says -
java.net.SocketException: Connection reset
So once the Server got a message i dont know how to get a second one, or any following one.
My main source code is:
public static void main (String[] args) {
int port = 13337;
BufferedReader msgFromClient = null;
PrintWriter msgToClient = null;
timeDate td = new timeDate(); //Class i did for myself to get time/date
ServerSocket s_socket = null;
try {
s_socket = new ServerSocket(port);
System.out.println("Server startet at "+td.getCurrDate()+" "+td.getCurrTime());
}
catch (IOException ioe) {
System.out.println("Server on Port "+port+" couldnt be created. \nException: "+ioe.getMessage());
}
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
msgFromClient = utils.createInputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Input Stream failed.\n Exception - "+ioe);
}
try {
msgToClient = utils.createOutputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Output Stream failed.\n Exception - "+ioe);
}
String input = null;
while (true) {
try {
input = msgFromClient.readLine();
} catch (IOException ioe) {
System.out.println(ioe);
}
if(input!=null) {
System.out.println("Jumping out of loop: "+input);
utils.processCode(input);
}
}
The both classes to create the streams look like this:
public static BufferedReader createInputStream (Socket socket) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return br;
}
public static PrintWriter createOutputStream (Socket socket) throws IOException {
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
return pw;
}
The "processCode" class then simply is a switch.
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You only accept one Connection an after this you are doing your handling. You need to open an new Thread for every connection
ExecutorService threadLimit = Executors.newFixedThreadPool(10);
while(true) {
Socket s = serverSocket.accept();
treadLimit.submit(new HandleThread(s));
}

Java Echo Server

Hello guys I am trying to do an echo Server by java but it is nnot working .. .I don't know why .. but it seems like the server is waiting the client and the client is waiting the server ... so they can't deliver the infromation to each other ..
here is the code
for the Server
ServerSocket server = null;
try {
server = new ServerSocket(3333);
System.out.println("Listening on 3333");
} catch (IOException ex) {
System.out.println("Error can't connect to 3333");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = server.accept();
} catch (IOException ex) {
System.out.println("Accept fail");
System.exit(1);
}
PrintWriter out = null;
try {
out = new PrintWriter(clientSocket.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(JavaApplication20.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(JavaApplication20.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String inputLine, outputLine;
while(!(inputLine=br.readLine()).equals("bye"))
{
out.print("echo: " + inputLine);
}
out.close();
br.close();
clientSocket.close();
server.close();
System.out.println("Server Exited");
and here is the code for the client
Socket client = null;
try {
client = new Socket("localhost", 3333);
System.out.println("Connected on 3333");
} catch (UnknownHostException ex) {
System.out.println("Couldn't connect to the server");
System.exit(1);
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter out = null;
BufferedReader in = null;
BufferedReader stdIn = null;
try {
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(KnockKnockClient.class.getName()).log(Level.SEVERE, null, ex);
}
stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer, fromUser;
while((fromUser=stdIn.readLine())!=null)
{
System.out.println("From user: "+ fromUser);
out.print(fromUser);
fromServer=in.readLine();
System.out.println(fromServer);
}
out.close();
stdIn.close();
in.close();
client.close();
System.out.println("client Exited");
Any Help with that ??
You're sending some string from the client ("Hello" for example), and you're trying to read it with readLine() on the server (and vice versa). readLine() will only return once it finds an EOL character, or once the input stream is closed.
Since the client doesn't send any EOL char, the server waits indefinitely, and the client also because it waits for the answer from the server.
Send "Hello\n", and it will work better.
After out.print(fromUser); use out.flush() in your client and server. flush will make sure it will right to the socket.
while((fromUser=stdIn.readLine())!=null)
{
System.out.println("From user: "+ fromUser);
out.print(fromUser);
out.flush();
fromServer=in.readLine();
System.out.println(fromServer);
}
out.close();
stdIn.close();
in.close();
client.close();
Regarding flush, Extracted from java doc.
Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

Sockets, BufferedReader.readline() - why the stream is not ready?

i'm learning java and i faced some problems with sockets. I developed a simple client-server app - kind of knock-knock, it performs 4 steps:
client sends some message to server
server recieves them and saves to file
server sends back to client some other messages
client recieves them and also saves to file
Problem appears on step #4: client doesn't recieve messages and never gets out the loop:
while ((inStr = in.readLine()) != null) {
writer.println(inStr);
}
where in is type of BufferedReader:
try {
socket = new Socket(ipAddress, 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
On server side messages are sent:
try {
socket = srvSocket.accept();
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
...
out.println("test from server #1");
out.println("test from server #2");
on client side i watched in.ready() - it returns false. On server side i watch out.checkError() - it returns true;
What am i doing wrong - why is the stream empty ?
Any help ia appreciated! :)
You are using public PrintWriter(OutputStream out, boolean autoFlush) which will flush automatically on new line or println. It does not autoflush after every write. You have to flush after every write.
Here is javadoc for the autoFlush param of the constructor:
A boolean; if true, the println, printf, or format methods will flush the output buffer
This might/might not solve your problem. But try keeping everything within Try Catch block. For eg: your ServerSocket initialization, writer blocks etc. If some error occurs, you might not be able to use writer anyhow, so there is no point in initializing it.
You might try writing to standard output stream for debugging instead of a file. Below code for Server/ Client is a minor variant of yours and its working.
Server:
Socket socket;
ServerSocket srvSocket;
BufferedReader in;
PrintWriter out;
try {
srvSocket=new ServerSocket(4444);
socket = srvSocket.accept();
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("test from server #1");
out.println("test from server #2");
} catch (IOException e) {
e.printStackTrace();
}
Client
Socket socket;
BufferedReader in;
PrintWriter out;
String inStr;
try {
socket = new Socket("127.0.0.1", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((inStr = in.readLine()) != null) {
System.out.println(inStr);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources