print BufferedReader while Socket remains open - java

What I want are just the responses from wunderground printed to the console:
public class Weather {
public static void main(String[] args) {
String host = "rainmaker.wunderground.com";
int port = 3000;
int c;
{
try (Socket socket = new Socket(host, port);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
System.out.println(socket.toString());
c = bufferedReader.read();
System.out.print((char) c);
}
} catch (IOException ex) {
System.out.println(ex + host + port);
System.exit(1);
} finally {
System.exit(1);
}
}
}
}
However, there's not much output to go on:
thufir#dur:~/NetBeansProjects/MudSocketClient$
thufir#dur:~/NetBeansProjects/MudSocketClient$ java -jar dist/MudSocketClient.jar
Socket[addr=rainmaker.wunderground.com/38.102.137.140,port=3000,localport=53550]
^Cthufir#dur:~/NetBeansProjects/MudSocketClient$
thufir#dur:~/NetBeansProjects/MudSocketClient$
Running telnet from the CLI, the connection works fine.

I found some old code:
public class InputOutput extends Observable {
private static final Logger log = Logger.getLogger(InputOutput.class.getName());
private Alias alias = new Alias();
public InputOutput() {
}
private void readFromConsole(final OutputStream outputStream) {
Thread read = new Thread() {
#Override
public void run() {
String line;
byte[] bytes;
Scanner scanner;
while (true) {
GameDataBean gameData = null;
scanner = new Scanner(System.in);
line = scanner.nextLine();
try {
gameData = alias.parseUserInput(line);
} catch (StringIndexOutOfBoundsException e) {
log.fine(e.toString());
}
if (gameData != null) {
setChanged();
notifyObservers(gameData);
} else {
bytes = line.getBytes();
try {
outputStream.write(bytes);
outputStream.write(10);
outputStream.flush();
} catch (IOException ex) {
log.fine(ex.toString());
}
}
}
}
};
read.start();
}
private void readInput(final InputStream inputStream) throws FileNotFoundException, IOException {
Thread readInput = new Thread() {
#Override
public void run() {
char ch = 0;
int intVal = 0;
StringBuilder sb = new StringBuilder();
try {
while ((intVal = inputStream.read()) != -1) {
ch = (char) intVal;
printToConsole(ch);
//logToFile(ch);
sb.append(ch);
if (intVal == 13) {
setChanged();
notifyObservers(sb.toString());
sb = new StringBuilder();
}
}
} catch (IOException ex) {
Logger.getLogger(InputOutput.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void logToFile(char c) throws IOException {
String fname = "weather.log";
File f = new File(fname);
f.createNewFile();
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fname, true)))) {
out.print(c);
out.flush();
}
}
private void printToConsole(char c) {
System.out.print(c);
}
};
readInput.start();
}
public void readWriteParse(final InputStream inputStream, final OutputStream outputStream) throws FileNotFoundException, IOException {
readFromConsole(outputStream);
readInput(inputStream);
}
}
I think it's that, when the socket is still open, it has to be multi-threaded, as I recall.

Related

SocketException recv failed, but why?

I've got a Client and a Server. The client simply sends 1 line of input to the server and then prints the response.
I'm getting a
SocketException (Software caused connection abort: recv failed)
[...]
at java.io.InputStreamReader.read(InputStreamReader.java:168)
at hw3.Client.readLine(Client.java:37)
at hw3.Client.main(Client.java:28)
The debugger tells me that the socket is not closed at the time of the read, what else can cause this exception?
I think I'm running into issues because of the threading, does anything stick out as "doing it wrong"?
public class Client
{
public static final int PORT = ReversingEchoServerDispatcher.PORT;
private static final String host = "localhost";
private static Socket sock;
public static void main(String[] args)
throws IOException
{
try(Socket sock = new Socket(host, PORT);
InputStreamReader clin = new InputStreamReader(sock.getInputStream());
OutputStream clout = sock.getOutputStream();
Scanner sc = new Scanner(System.in))
{
Client.sock = sock;
byte[] cl = sc.nextLine().getBytes("UTF-8");
clout.write(cl);
System.out.println(readLine(clin));
}
}
private static String readLine(InputStreamReader in)
throws IOException
{
StringBuilder sb = new StringBuilder();
for(int i = in.read(); i != -1; i = in.read())
{
char c = (char) i;
if(c != '\n') sb.append(c);
else break;
}
return sb.toString();
}
}
public class ServerDispatcher
{
public static final int PORT = 8034;
public static void main(String[] args)
{
try (ServerSocket serversock = new ServerSocket(PORT))
{
while(true)
{
Socket socket = serversock.accept();
ServerLogic sv = new ServerLogic(socket);
new Thread(() -> {
try {
sv.run();
} catch (IOException ex) {
ex.printStackTrace(System.err);
}
}).start();
}
}
catch(IOException e)
{
e.printStackTrace(System.err);
}
}
}
For the record, the ServerLogic class looks something like the following. My exit code is 1, not -999, so it's not that socket.close() is failing
class ServerLogic
{
Socket socket;
public
ServerLogic(Socket s)
{
this.socket = s;
}
public void run()
throws IOException
{
try(InputStreamReader in = new InputStreamReader(socket.getInputStream());
OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream()))
{
StringBuilder sb = new StringBuilder();
while(in.ready()) {
char c = (char) in.read();
if(c == '\n') {
String str = process(sb);
if(str != null) out.write(str);
else return;
} else {
sb.append(in.read());
}
}
} finally {
try {
socket.close();
} catch(IOException ex) {
ex.printStackTrace(System.err);
System.exit(-999);
}
}
}
private static String process(StringBuilder sb)
{ /* ... */ }
The server is expecting a newline \n to terminate the input but you never send one from the client. sc.nextLine() returns the input line but does not include the terminating newline. The while(in.ready()) loop eventually ends and the server closes the socket without ever sending a response.

Why is this exception thrown and how to recover from it?

I am creating a remote-desktop screenshot application. I have two methods on the server 1) To read the Image from client 2) to read the list of task running on the client). But everytime I try to read the client's input stream an EOF excetion is thrown. The stakctrace of the exception is
java.io.EOFException at
java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2323)
at
java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2792)
at
java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:799)
at java.io.ObjectInputStream.(ObjectInputStream.java:299) at
remoteserverclient.original.ScreenServer$ServerThread.run(ScreenServer.java:254)
Here is the code on the server where the exception is thrown
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
Object obj = in.readObject();
if (obj instanceof Rectangle) {
CaptureScreen(obj, in);
} else if (obj instanceof String) {
CaptureList(in);
}
Here is the complete code for the client
public class ScreenClient {
static Socket server;
public static void main(String[] args) throws Exception {
try {
while (true) {
server = new Socket("localhost", 5494);
BufferedReader bf = new BufferedReader(new InputStreamReader(server.getInputStream()));
String s;
s = bf.readLine();
System.out.println(s);
if (s.contains("execute")) {
new ClientMessageThread().start();
}
if (s.contains("getProcessList")) {
new ClientFetchProcessThread().start();
}
}
} catch (Exception e) {
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
public static class ClientMessageThread extends Thread {
Socket server;
public ClientMessageThread() {
try {
server=new Socket("localhost",5494);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedImage screen;
Robot robot = new Robot();
Rectangle size = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
screen = robot.createScreenCapture(size);
int[] rgbData = new int[(int) (size.getWidth() * size.getHeight())];
screen.getRGB(0, 0, (int) size.getWidth(), (int) size.getHeight(), rgbData, 0, (int) size.getWidth());
OutputStream baseOut = server.getOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baseOut);
out.writeObject(size);
for (int x = 0; x < rgbData.length; x++) {
out.writeInt(rgbData[x]);
}
out.flush();
server.close();
//added new
} catch (Exception e) {
System.err.println("Disconnected From server ->" + e.getMessage());
}
}
}
public static class ClientFetchProcessThread extends Thread {
Socket server;
public ClientFetchProcessThread() {
try {
server=new Socket("localhost",5494);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void run() {
try {
PrintWriter ps;
System.out.println("\n\n********");
StringBuilder builder = new StringBuilder("");
String query = "tasklist";
Runtime runtime = Runtime.getRuntime();
InputStream input = runtime.exec(query).getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
ps = new PrintWriter(server.getOutputStream(), true);
while ((line = commandResult.readLine()) != null) {
builder.append(line + "\n");
//byte[] responseClient=s.getBytes();
ps.write(builder.toString());
System.out.println(builder.toString());
}
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You're both printing and writing objects to port 5494 from the client. The server only reads objects.
Sort it out.
The exception being thrown is EOFException (End of file exception).
ObjectInputStream throws EOFException when it reaches the end of the input. That's standard behaviour. Are you catching all exceptions thrown by in.readObject()?
Documentation:
http://docs.oracle.com/javase/7/docs/api/java/io/ObjectInputStream.html

br.readline() gets stuck while br.read() works

I am making a simple ftp client/server program which on command from the clients lists files, tells the current directory, downloads files
My client code works fine since i have already tested it with a working server. However the server that i have designed gets stuck in the run() function on the line String message = br.readline(); If instead i use the br.read(), then it works but i need command in form of a string to know which file i have to download whereas br.read() returns int. Here's my code, i have used threading.
public class Myserver {
static final int PortNumber = 108;
static ServerSocket MyService;
static Socket clientSocket = null;
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File directory;
directory = new File(System.getProperty("user.home"));
try {
MyService = new ServerSocket(PortNumber);
String cd = directory.toString();
System.out.println(cd);
System.out.println("Listening on " + PortNumber);
while(true) {
clientSocket = MyService.accept();
Connecthandle a = new Connecthandle(clientSocket, directory);
a.run();
}
}
catch (IOException e) {
System.out.println(e);
}
}
static class Connecthandle extends Thread {
File Directory;
Socket clientsocket;
// Constructor for class
Connecthandle(Socket clients, File dir) {
clientsocket = clients;
Directory = dir;
}
// Works Fine
void listfiles() throws IOException {
String []Listfile = Directory.list();
String send = "";
for (int j = 0; j < Listfile.length; j++) {
send = send + Listfile[j] + ",";
}
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(send);
GoingOut.flush();
GoingOut.close();
}
// Works Fine
void currentdirectory() throws IOException {
String cd = Directory.toString();
String cdd = "resp," + cd;
System.out.println(cdd);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
GoingOut.writeBytes(cdd);
GoingOut.flush();
GoingOut.close();
System.exit(0);
}
void sendfiles(String fileName) {
try {
File nfile = new File(fileName);
DataOutputStream GoingOut = new DataOutputStream(clientsocket.getOutputStream());
if ( (! nfile.exists()) || nfile.isDirectory() ) {
GoingOut.writeBytes("file not present");
} else {
BufferedReader br = new BufferedReader(new FileReader(nfile));
String line;
while ((line = br.readLine()) != null) {
line = br.readLine();
GoingOut.writeBytes(line+"\n");
}
GoingOut.flush();
GoingOut.close();
br.close();
}
} catch (IOException e) {
System.out.println("Unable to send!");
}
}
#SuppressWarnings("deprecation")
public void run() {
try {
DataInputStream comingin = new DataInputStream(clientsocket.getInputStream());
InputStreamReader isr = new InputStreamReader(comingin, "UTF-8");
BufferedReader br = new BufferedReader(isr);
System.out.println("here");
// if (br.ready())
String message = br.readLine(); // Code gets stuck here, if i use br.read() it works, but i need string output.
if (message.equals("listfiles\n")) {
listfiles();
} else if (message.equals("pwd")) {
currentdirectory();
} else if (message.contains("getfile,")) {
String fileName = new String(message.substring(8, message.length()));
sendfiles(fileName);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
clientsocket.close();
} catch (IOException e) {}
}
}
}
}
If readLine() is blocking and you are sending data, you aren't sending a newline.

Java reading message from socket is not sending full message

hello I am using this method to read a message:
public String readMessage() {
int read = -1;
byte[] buffer = new byte[5*1024];
byte[] redData;
try {
while ((read = this.session.getInputStream().read(buffer)) > -1) {
redData = new byte[read];
System.arraycopy(buffer, 0, redData, 0, read);
return new String(redData,"UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
And when I write something like "hello how are you today?"
Response (Exact format, including these new lines):
[/127.0.0.1:54930]:
[/127.0.0.1:54930]: are
[/127.0.0.1:54930]: you
[/127.0.0.1:54930]: today?
Thats how I read chat messages, first I check which packet was requested, if the packet type was 0, then I get instance of packethandler, and pass the client object to the Chat handling packet which will read the message here, like this:
public void startClientService() throws IOException {
while(true) {
int packetType = this.in.read();
packets.getPacket(packetType);
}
}
public void getPacket(int packetType) {
switch (packetType) {
case 0:
chat.processPacket(this.client);
break;
}
}
And the chat packet:
#Override
public void processPacket(Session c) {
String clientMessage = c.readMessage();
System.out.println("[" + c.getStream().getRemoteSocketAddress() + "]: " + clientMessage.toString());
}
And there the print message happens.
Why does it print parts of the messages, in new lines? not even the full message.
This is my client:
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 43594);
Scanner r = new Scanner(System.in);
PrintWriter out = new PrintWriter(socket.getOutputStream());
String input;
while(true) {
input = r.next();
if (input != null) {
sendMessage(input, out);
}
}
}
public static void sendMessage(String message, PrintWriter out) {
out.write(0);
out.flush();
out.write(message + "\n");
out.flush();
}
Thanks.
Session:
public class Session extends Thread implements Runnable {
private Socket session;
private Client client;
private PrintWriter out;
private BufferedReader in;
private PacketHandler packets;
public Session(Socket session) {
this.session = session;
this.client = new Client(this);
try {
this.setStream();
} catch (IOException e) {
e.printStackTrace();
}
this.packets = new PacketHandler(this);
System.out.println("[New session created]: " + session.getRemoteSocketAddress());
}
public void run() {
try {
this.startClientService();
} catch (IOException e) {
e.printStackTrace();
}
}
public Socket getStream() {
return this.session;
}
public void setStream() throws IOException {
this.out = new PrintWriter(this.session.getOutputStream());
this.in = new BufferedReader(new InputStreamReader(this.session.getInputStream()));
}
public Client getClient() {
return this.client;
}
public String readMessage() {
int read = -1;
byte[] buffer = new byte[5*1024];
byte[] redData;
try {
while ((read = this.session.getInputStream().read(buffer)) > -1) {
redData = new byte[read];
System.arraycopy(buffer, 0, redData, 0, read);
return new String(redData,"UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void startClientService() throws IOException {
while(true) {
int packetType = this.in.read();
packets.getPacket(packetType);
}
}
public void destruct() throws IOException {
this.session.close();
System.out.println("Session killed");
}
}
looks like you are returning as soon as you get some data from stream.
while ((read = this.session.getInputStream().read(buffer)) > -1) {
redData = new byte[read];
System.arraycopy(buffer, 0, redData, 0, read);
return new String(redData,"UTF-8");
}
Read the data completely and make a string object out of it and return it
BufferedReader br = new BufferedReader(new InputStreamReader(this.session.getInputStream()));
String msg = br.readLine();
br.close();
return msg;
try this way. This will give you entire data to a buffer and can return as line of string.No need of loop
The the amount of data returned from one call to read has no relationship to how the
data divided when sent. One send can result in any number of reads, and multiple sends
may be combined into one read.

Overriding the run() method to accept a parameter from the command line

I'm trying to search a word (from a file) specified in the command line using client/server. Here is my code, however it displays nothing when the client part is run. To run the server, type -s <port number> <file.txt> and for the client, -c localhost <port number> <word to be searched> in the command line.
import java.net.*;
import java.util.*;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static String target;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
target = args[3];
}
else if(args[0].equals("-s")){
System.out.println("Server");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException{
String hostname = args[1];
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
Scanner userEntry = new Scanner(System.in);
String response;
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
serverSocket = new ServerSocket(port);
do {
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
public ClientHandler3(Socket socket, String file) {
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String target;
String message = "";
target= args[3];
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
(Thanks to Sir JB Nizet for some modifications and advice) I'm having a problem in target= args[3]; in class ClientHandler3 because I know it makes no sense in overriding. I'm new in this field of programming and I need your help. Please help me figure things out. Thank you!
EDIT
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.*;
public class quotes {
public static InetAddress host;
public static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
if(args[0].equals("-c")){
Client(args);
}
else if(args[0].equals("-s")){
System.out.println("SERVER KA!!!");
Server(args);
}
}
#SuppressWarnings("resource")
public static void Client(String[] args) throws IOException
String hostname = args[1];
String target, response;
if(hostname.equals("localhost")) host = InetAddress.getLocalHost();
else host = InetAddress.getByName(hostname);
int port = Integer.parseInt(args[2]);
target = args[3];
Socket socket = new Socket(host, port);
Scanner input = new Scanner(System.in);
Scanner networkInput = new Scanner(socket.getInputStream());
PrintWriter networkOutput = new PrintWriter(socket.getOutputStream(), true);
// Set up stream from keyboard entry...
Scanner userEntry = new Scanner(System.in);
networkOutput.println(target);
response = networkInput.nextLine();
while(!response.equals("|")){
// Display server's response to user ...
System.out.println("\n " + response);
response = networkInput.nextLine();
}
}
public static void Server(String[] args) throws IOException {
int port = Integer.parseInt(args[1]);
String file = args[2];
String target = "";
serverSocket = new ServerSocket(port);
do {
// Wait for client...
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
ClientHandler3 handler = new ClientHandler3(client, file, target);
handler.start();
}while(true);
}
}
class ClientHandler3 extends Thread {
private Socket client;
private Scanner input;
private PrintWriter output;
private ArrayList<String> quotes;
private String target;
public ClientHandler3(Socket socket, String file, String target) {
// Set up reference to associated socket...
client = socket;
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
this.target = reader.readLine();
String line = reader.readLine();
try {
int ctr = 0;
quotes = new ArrayList<String>();
while(line != null){
quotes.add(ctr, line);
ctr++;
line = buffer.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(), true);
}
catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
String message = "";
target= input.nextLine();
for(int i = 0; i<quotes.size(); i++){
if(quotes.get(i).toUpperCase().contains(target.toUpperCase())){
output.println(quotes.get(i));
}
}
output.println("|");
try {
if (client != null) {
System.out.println("Closing down connection...");
client.close();
}
}
catch(IOException e) {
System.out.println("Unable to disconnect!");
}
}
}
Set target as a field of ClientHandler3 so you can use it inside run() method.
class ClientHandler3 extends Thread {
...
private String target;
...
and use:
this.target = reader.readLine();
just before
String line = reader.readLine();
line.

Categories