Printing on Printronix T5000r over ethernet using Java - java

I have a problem with printing on this specific printer.
public void print(String fileName, String printerIp) {
try {
BufferedReader streamIn = new BufferedReader(new FileReader(fileName));
String line;
Socket socket = new Socket(printerIp, 9100);
Writer writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
while ((line = streamIn.readLine()) != null) {
writer.write(line);
}
writer.flush();
socket.close();
streamIn.close();
}
The situation looks like everything is fine but the printer do not print, when I use other program to print everything works fine.
Any thoughts ?

The solution is to write whole file to the printer.
public void printFile(File file, String printerIp) throws PrintException, IOException {
Socket socket = new Socket(printerIp, 9100);
FileInputStream fileInputStream = new FileInputStream(file);
byte [] mybytearray = new byte [(int)file.length()];
fileInputStream.read(mybytearray,0,mybytearray.length);
OutputStream outputStream = socket.getOutputStream();
outputStream.write(mybytearray,0,mybytearray.length);
//Curious thing is that we have to wait some time to make more prints.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
outputStream.flush();
outputStream.close();
socket.close();
fileInputStream.close();
}

Related

Sent file with socket in java

I want to send file from client to server using socket.
But at the server, I only receive the first line. What is the problem?
Server Code
public static void main(String ars[]){
int port = 1000;
try {
ServerSocket sercoc = new ServerSocket(port);
System.out.println("dkjd");
while (true){
Socket soc = sercoc.accept();
InputStream flux = soc.getInputStream();
BufferedReader entree = new BufferedReader(new InputStreamReader(flux));
String message = entree.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client Code
public static void main(String args[]){
String hote = "127.00.0.1";
int port = 1000;
FileReader input = null;
File file = new File("src/view/files/temperature2.txt");
Socket soc = null;
try {
soc = new Socket(hote,port);
OutputStream flux = soc.getOutputStream();
OutputStreamWriter sortie = new OutputStreamWriter(flux);
try {
input = new FileReader("src/view/files/temperature2.txt");
char c;
while ((c = (char) input.read()) != -1){
sortie.write(c);
//sortie.write("\n");
}
} finally {
if (input != null){
input.close();
}
}
sortie.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
If I use BufferedReader I found errors and I can't receive anything!
in my code I have implemented the transfer of photo, txt and zip files through ObjectOutputStream and ObjectInputStream.
code:
// output
ObjectOutputStream objectOutput = new ObjectOutputStream(connection.clientSocket.getOutputStream());
objectOutput.writeObject(your_file);
// input
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
buffer = (byte[]) ois.readObject();

Java BufferedWriter and OutputStream .close() method

I'm new in java and there is a question about BufferedWriter and OutputStream closing.
I have some logic, where it is inconvenient to use try-with-resources:
public static void writeFile(String fileName, String encoding, String payload) {
BufferedWriter writer = null;
OutputStream stream = null;
try {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
stream = needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So, i have to close all resources by myself. Should i close OutputStream AND BufferedWriter? Or it is ok to close just BufferedWriter?
Is everything ok with my code?
No, Leave it to Java, let it handle it:
public static void writeFile(String fileName, String encoding,
String payload) {
boolean needGzip = payload.getBytes(Charset.forName(encoding)).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz")
: new File(fileName);
try (OutputStream stream = needGzip ? new GZIPOutputStream(
new FileOutputStream(output)) : new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
It is OK to just close the BufferedWriter. If you follow the Javadoc you will see that it closes all nested streams.
If you close BufferedWriter its stream will be closed too but BufferedWriter and OutputStream both implements Closeable. So if you want you can just use try with resource to handle the close for you
for example :
public static void writeFile(String fileName, String encoding, String payload) {
File output = new File(fileName);
try (OutputStream stream = new FileOutputStream(output);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
Edit: Added getStream to check if it needs gzip stream or no
Note: This answer is just an "update" of your code, i'm not sure what are you trying to do in general, so it may not be the best solution for your program
public static void writeFile(String fileName, String encoding, String payload) {
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(getStream(fileName, encoding, payload), encoding))) {
writer.write(payload);
} catch (IOException e) {
e.printStackTrace();
}
}
public static OutputStream getStream(String fileName, String encoding, String payload) throws IOException {
boolean needGzip = payload.getBytes(encoding).length > gzipZize;
File output = needGzip ? new File(fileName + ".gz") : new File(fileName);
return needGzip ? new GZIPOutputStream(new FileOutputStream(output)) : new FileOutputStream(output);
}

Java: Buffered Reader waiting for input before updating

I am programming a small ChatServer program, and I've nailed down the error to this part of the client code
public void run() {
Client client = new Client();
try {
Socket s = new Socket("localhost", 25555);
client.os = new DataOutputStream(s.getOutputStream());
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
while (!exit){
String str = Input.read_string();
client.os.writeUTF(ID+"=CLID"+str.toLowerCase());
client.os.flush();
System.out.println(br.readLine());
}
} catch ( IOException e) {
e.printStackTrace();
}
}
The Input.read_string() code is the following:
class Input{
public static String read_string() {
String read="";
try {
read = new BufferedReader(new InputStreamReader(System.in), 1).readLine();
} catch (IOException ex) {
System.out.println("error reading from the input stream!");
}
return read;
}
}
When I put the System.out.println(br.readLine()); at the beginning of the while loop the first time another client chats, but after that one has to input to get the next update.
Also, this may be fixed with the last error, but when it does update, it is the last thing the other client sent.

Connection Reset in Java

I've been trying to fix this error for days now. Really. I just don't get it. The code is simple enough.. Why is it not working?
public class server
{
public static void main(String[] args)
{
String fileName = null;
try
{
ServerSocket ss = new ServerSocket(9999, 3);
Socket dataSocket = ss.accept();
System.out.println("Server: Connection Established");
InputStream is = dataSocket.getInputStream();
//BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner sc = new Scanner(dataSocket.getInputStream());
while(sc.hasNextByte())
{
System.out.println("True");
fileName = fileName+sc.next();
}
FileWriter fw = new FileWriter("server"+fileName);
while(dataSocket != null)
{
fw.write(is.read());
}
fw.flush();
dataSocket.close();
ss.close();
/*String[] nameParts;
nameParts = fileName.split(".");
File f = new File(nameParts[0]+"."+nameParts[1]);
FileOutputStream fos = new FileOutputStream(f);
System.out.println(nameParts[0]);*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Above is the server code. The client code is below:
public class client
{
public static void main(String[] args)
{
// Read a file
try
{
Socket dataSocket = new Socket();
dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
System.out.println("Client: Connection Established");
OutputStream os = dataSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String fileName = "text.txt";
pw.write(fileName);
File f = new File(fileName);
Scanner sc = new Scanner(f);
/*while(sc.hasNextInt())
{
pw.write(sc.nextInt());
}*/
//pw.flush();
//pw.close();
//dataSocket.close();
/*String[] nameParts = new String[2];
nameParts = args[0].split(".");
while(sc.hasNextByte())
{
os.write(sc.nextByte());5
}*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
At first, both client and server just kept waiting for each other to speak, like two shy teenagers. After a few changes, this started to happen. I get the Connection Reset error. Please help. Deadlines!
sc.hasNextByte() remains true until the peer has closed the connection. So you will never get out of this loop. You need to send the filename length ahead of the filename, so you know how much of the incoming data is the filename. Then read the filename, open the file, and read and copy the rest of the stream until EOS.
Optionally, you can write your file name with a lien as below:
pw.write(fileName + "\n");
Or user some writer to writeLine(fileName ).
And in server side, use bufferedReader to read line by line:
while ((line = br.readLine()) != null) {
....
}
Then it can finish the loop if the client is closed.

InputStreamReader throws IOException

I'm trying to use an InputStreamReader to read bytes sent by a socket
I have
InputStreamReader in = new InputStreamReader(socket.getInputStream());
in.read();
This throws an IOException :(. I know the socket should be sending something but it keeps throwing the error.
The actual error message and stack trace would indeed be useful.
You could try using a BufferedReader and using readLine to make sure you are getting something.enter link description here
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
Found here
That is expected behaviour, IOException is signalling that there is nothing to read, most probably socket has not connected properly. This question should be closed.

Categories