How to read lines of input from server? (java client console application) - java

I've connected to an already existent server that contains lines of strings I need to read in. Given that I only need to read in a String type, which input reader would work here so I could read line by line in my While loop? Here's my simple Client:
public class Client
{
public static final int PORT_NUMBER = 8888;
public static void main(String[] args)
{
int port = PORT_NUMBER;
String content;
OutputStream output;
InputStream input;
Socket s = null;
try
{
s = new Socket("server.example.exp", port);
output = s.getOutputStream();
input = s.getInputStream();
System.out.println("Connected to " + s.getInetAddress() + " on port " + s.getPort());
}
catch (IOException e) {System.err.println(e);}
while (true)
{
try
{
//read next line from server
}
catch (EOFException eof){
System.out.println("eof encountered" + eof.getMessage());
break;
}
catch (OptionalDataException ode){System.out.println("OptionalDataException" + ode.getMessage());}
catch (IOException ioe){System.out.println("IOException on read object");}
catch (ClassNotFoundException cnf){System.out.println("ClassNotFoundException");}
}
}
}
I know it's a very basic question, I'm just having trouble getting started, is all. I appreciate any clarification. Thanks.

To read from an InputStream, you can wrap it in a InputStreamReader, and then a BufferedReader, from which you can readLine:
BufferedReader input;
input = new BufferedReader(new InputStreamReader(s.getInputStream()));
Then:
while(true){
try{
input.readLine();//Read from server
}

Add the folloWing line before your while
BufferedReader inp2 = new BufferedReader(new InputStreamReader(inp));
while (true) {
try {
inp2.readLine();
}
}

Related

Why hasNextLine() blocks executing of program while getting data from console?

Today I was trying to write some, lets say, internet communicator.
I'm learning basics of Java (from instructables) and now it's time for network programming.
What I want my program to do:
If there is any data on input stream from network - get data, put it into string and print in a console.
If there is data in console - put it into string and send it by network.
When I try only send data from client app to server and print it in server console - everything works fine. But then I have different code (without getting and sending data two way).
I know that problem is in lines inside while(true) statements in line if(cin.hasNextLine()). I don't understand why it blocks whole app when it should be just returning false or true if there isn't or there is data in console (from keyboard).
The annoying is that it's working perfectly with reading files.
Oh. And also I tried to check IF data which I didn't typed into console is "". It didn't solved my problem.
Server code:
import java.net.*;
import java.io.*;
import java.util.*;
import java.time.LocalTime;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port, 0);
serverSocket.setSoTimeout(30000);
}
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " + server.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " + server.getLocalSocketAddress());
FileWriter plik = new FileWriter("/home/greg/Dokumenty/logizserwera.txt", true);
System.out.println("StartTime: " + LocalTime.now());
Scanner cin = new Scanner(System.in);
String stringReadyToSend, stringGotFromClient = null;
while(true) {
System.out.println("Before hasnextline");
if(cin.hasNextLine()) {
stringReadyToSend = cin.nextLine();
out.writeUTF(stringReadyToSend);
}
if(in.available() != 0) {
stringGotFromClient = in.readUTF();
// EOT means End Of Transmission
if(stringGotFromClient.equals("EOT")) break;
else System.out.println("Message from client: " + stringGotFromClient();
}
else System.out.println("No message");
break;
}
System.out.println("EndTime: " + LocalTime.now());
server.close();
plik.close();
}
catch(SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
}
catch(IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 6066;
try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}
}
}
And client code:
import java.net.*;
import java.io.*;
import java.util.*;
public class GreetingClient {
public static void main(String[] args) {
String serverName = "localhost";
Scanner cin = new Scanner(System.in);
int port = 6066;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
String lineReadyToSend, lineGotFromServer;
while(cin.hasNextLine()) {
if(cin.hasNextLine()) {
// EOT means End Of Transmission
lineReadyToSend = cin.nextLine();
if(lineReadyToSend.equals("EOT")) {
out.writeUTF(lineReadyToSend);
break;
}
else out.writeUTF(lineReadyToSend);
}
if(in.available() != 0) {
lineGotFromServer = in.readUTF();
System.out.println("Message from server: " + lineGotFromServer);
}
}
out.writeUTF("EOT");
client.close();
System.out.println("End of transmission. Server disconnected");
}catch(IOException e) {
e.printStackTrace();
}
}
}
You are using cin which is a Scanner for the System.in
Practically that just scans if there are entered lines on the console. Perhaps try doing that with the data input stream (in) on your server.
Well, everything looks god. Just a cuestion, do you execute both applications at same time? Well, if it's the case, could be the access to System.in resource. Remember this is a static field, and not instantiated. Try to run one of them in other location. A second hint: use try clause and watch the errors if there are, and use debuging or resource monitor tools to detect the problem.

What determines in this code what is sent back to the client? TCP Sockets

In the code below, what determines what will be sent back to the client (the PHP page). I am trying to alter this so that it sends a variable back to the PHP page with an error message that is defined based on actions made in my java code.
Edit: To answer some questions, what I am trying to do is this.
Send a string to the java script with a socket and convert it to a variable to be used in the java script. It will run through some if statements and I need to set the error statements to a variable lets say "reply". I need to send "reply" then back to the PHP file.
public class MyJavaServer {
public static void main(String[] args) {
int port = 20222;
ServerSocket listenSock = null; //the listening server socket
Socket sock = null; //the socket that will actually be used for communication
try {
listenSock = new ServerSocket(port);
while (true) { //we want the server to run till the end of times
sock = listenSock.accept(); //will block until connection recieved
BufferedReader br =
new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw =
new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
String line = "";
while ((line = br.readLine()) != null) {
bw.write("PHP said: " + line + "\n");
bw.flush();
}
//Closing streams and the current socket (not the listening socket!)
bw.close();
br.close();
sock.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
If I get your question right, the line where the answer gets sent to the peer is
bw.write("PHP said: " + line + "\n");
which writes the given string to bw.

How to send commands and receive responses to OSGi console via a Java Socket?

I want to run OSGi framework on another computer (in a main method). So I wanted to know is there any way to connect to the OSGi console from the other computer and manage bundles?
I thought maybe using a java.net.Socket would help, and that's how I implemented that. I've used 2 threads. one for processing user input stream, and the other one that processes OSGi Console response. This is the first thread (processes user input stream):
configMap.put("osgi.console", "6666");
Framework fwk = ff.newFramework(configMap);
try {
fwk.start();
} catch (BundleException e) {
e.printStackTrace();
}
//__________________________________________________________________//
try {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
ConsoleOutputReciever fr = new ConsoleOutputReciever();
new Thread(fr).start();
while (true) {
String userInput = "";
while ((userInput = stdIn.readLine()) != null) {
System.out.println("--> " + userInput);
out.write(userInput + "\n");
out.flush();
}
System.out.println("2");
}
} catch (Exception e1) {
e1.printStackTrace();
}
This is the second thread (processes OSGi Console response):
public class ConsoleOutputReciever implements Runnable {
public Scanner in = null;
#Override
public void run() {
printlnInfo("ConsoleOutputReciever Started");
try {
Socket socket = new Socket(InetAddress.getByName("0.0.0.0"), 6666);
printlnInfo("Socket has been created: " + socket.getInetAddress() + ":" + socket.getPort());
String osgiResponse = "";
in = new Scanner(socket.getInputStream());
try {
while (true) {
in = new Scanner(socket.getInputStream());
while (in.hasNext()) {
System.out.println("-- READ LOOP");
osgiResponse = in.nextLine();
System.out.println("-- " + osgiResponse);
}
}
} catch (IllegalBlockingModeException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
but I only receive the first response of the OSGi console. like this:
--READ LOOP
--
--READ LOOP
ss
--> ss
Any ideas about the problem or any other way to connect to OSGi console remotely?
you are using blocking io, thus your inner while loop will never finish until the socket is closed. you need 2 threads to accomplish this with blocking io streams. 1 thread reads from stdin and writes to the socket output stream, the other thread reads from the socket input stream and writes to stdout.
also, you probably want to write a newline after sending the userInput to the osgi console (Scanner.nextLine() eats the newline).
lastly, you don't generally want to use the Print* classes when working with sockets as they hide IOExceptions.
Instead of building your own thing you might want to use one of the remote shells that are available, for example the Apache Felix one at http://felix.apache.org/site/apache-felix-remote-shell.html

Java Sockets and Blackberry programming

i'm new to programming and I'm trying to build a blackberry IRC Client, I made it connect to a server, join a channel and say something, but how can I receive messages ? I don't know how to make a loop to wait for messages, can somebody help me ? here is my code:
package com.rim.samples.device.socketdemo;
import java.io.*;
import javax.microedition.io.*;
import net.rim.device.api.ui.*;
public class ConnectThread extends Thread
{
private InputStream _in;
private OutputStreamWriter _out;
private SocketDemoScreen _screen;
// Constructor
public ConnectThread()
{
_screen = ((SocketDemo)UiApplication.getUiApplication()).getScreen();
}
public void run()
{
StreamConnection connection = null;
String user = "Cegooow";
String channel = "#oi";
try
{
_screen.updateDisplay("Opening Connection...");
String url = "socket://" + _screen.getHostFieldText() + ":6667" + (_screen.isDirectTCP() ? ";deviceside=true" : "");
connection = (StreamConnection)Connector.open(url);
_screen.updateDisplay("Connection open");
_in = connection.openInputStream();
_out = new OutputStreamWriter(connection.openOutputStream());
StringBuffer s = new StringBuffer();
_out.write("NICK " + _screen.getNickText() + "\r\n");
_out.write("USER " + user + "8 * : Java Bot\r\n");
_out.write("JOIN " + channel + "\r\n");
_out.write("PRIVMSG " + channel + " " + _screen.getMessageFieldText() + "\r\n");
_screen.updateDisplay("Done!");
}
catch(IOException e)
{
System.err.println(e.toString());
}
finally
{
_screen.setThreadRunning(false);
try
{
_in.close();
}
catch(IOException ioe)
{
}
try
{
_out.close();
}
catch(IOException ioe)
{
}
try
{
connection.close();
}
catch(IOException ioe)
{
}
}
}
}
I used the sockets demo sample on blackerry jre, thanks
In your code you have an OutputStreamWriter _out to write to the Server, the incoming connection _in (InputStream) is unused. You should expect any incoming data there...
The simplest example I can think of would be like this:
// process the inputstream after writing to _out - in single threaded app
Reader reader = new InputStreamReader(_in);
int data;
while((data = reader.read()) != -1 ){
System.out.println((char) data); // do something with the char
}
reader.close();
In practice, it would be better to use a BufferedReader. Also, if you are building a chat application it might be beneficial to create a new thread to process incoming data and another thread for outgoing data.
Once you get your input stream reader handle you can loop until connection closes
BufferedReader reader = new BufferedReader(_in);
while(true) {
String line = reader.readLine();
// do something...
}

RXTX serial connection - issue with blocking read()

I am trying to use the RXTX library for blocking serial communication on Windows (XP and 7). I have tested the connection with Hyperterminal in both ends, and it works flawlessly.
I set up the connection with the following code: (exception handling and defensive checks omitted for clarity)
private InputStream inStream;
private OutputStream outStream;
private BufferedReader inReader;
private PrintWriter outWriter;
private SerialPort serialPort;
private final String serialPortName;
public StreamComSerial(String serialPortName) {
this.serialPortName = serialPortName;
CommPortIdentifier portIdentifier;
portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = null;
commPort = portIdentifier.open(this.getClass().getName(),500);
serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(4800,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
inStream = serialPort.getInputStream();
outStream = serialPort.getOutputStream();
inReader = new BufferedReader(new InputStreamReader(inStream, Settings.getCharset()));
outWriter = new PrintWriter(new OutputStreamWriter(outStream, Settings.getCharset()));
When I use
outWriter.println("test message");
flush();
the message is recieved fine on the other end, but calling
inReader.readLine()
imidiately returns "java.io.IOException: Underlying input stream returned zero bytes".
I then decided to try and implement my own blocking read logic and wrote this:
public String readLine() throws IOException {
String line = new String();
byte[] nextByte = {-1};
while (true) {
nextByte[0] = (byte)inStream.read();
logger.debug("int read: " + nextByte[0]);
if (nextByte[0] == (byte)-1) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
logger.debug("byte read: " + nextByte[0]);
line = line + new String(nextByte);
if (nextByte[0] == (byte)13) { // 13 is carriage return in ASCII
return line;
}
}
}
But this code goes in an infinite loop and "nextByte[0] = (byte)inStream.read();" assigns -1 no matter what is sent over the serial connection. In addition, the other end stutters quite badly and only lets me send a character every 1-3 sec. and hangs for a long time if I try to send many characters in a short burst.
Any help very appreciated.
*edit - using inStream.read(nextByte) instead of "nextByte[0] = (byte)inStream.read();" does not write to the nextByte variable, no matter what I send to it through the serial connection.
*edit2 - as my code works flawlessly with the SUN javax.comm lib and a win32com.dll I got from a friend, I have ceased trying to make it work with RXTX. I am not interested in unblocking communication, which seems to be the only way other people can make RXTX work.
Use RXTX-2.2pre2, previous versions have had a bug which prevented blocking I/O from working correctly.
And do not forget to set port to blocking mode:
serialPort.disableReceiveTimeout();
serialPort.enableReceiveThreshold(1);
I think the code you wrote in your own readLine implementation is buggy. nextByte[0] is never restored to -1 after the first character is read.
You should try to use the value returned by inStream.read(nextByte) to state the number of bytes read from the stream instead of the value of your byte array.
Anyway I think you should go for an event based method of reading the inputs with a SerialPortEventListener:
serialPort.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent evt) {
switch (evt.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
dataReceived();
break;
default:
break;
}
}
});
serialPort.notifyOnDataAvailable(true);
it may not be blocking but when the stream is empty, just catch the IOE and keep reading from it. This is what I do with RXTX-2.1-7 and it works fine, I use it to read and write to an arduino:
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run() {
Boolean keepRunning = true;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while (keepRunning) {
try {
while ((line = br.readLine()) != null) {
//DO YOUR STUFF HERE
}
} catch (IOException e) {
try {
//ignore it, the stream is temporarily empty,RXTX's just whining
Thread.sleep(200);
} catch (InterruptedException ex) {
// something interrupted our sleep, exit ...
keepRunning = false;
}
}
}
}
}
I have solved this way
try
{
if(input.ready()==true)
{
String inputLine=input.readLine();
System.out.println(inputLine);
}
} catch (Exception e)

Categories

Resources