i'm writing a java program that sends and receives data from a printer, i can get the command but i can't read in any way a response.
Socket s = new Socket(ip, port);
System.out.println("-----------------> MioSocket closed: "+s.isClosed());
OutputStream out = s.getOutputStream();
System.out.println("-----------------> InputStream: "+out.toString());
DataOutputStream output = new DataOutputStream(out);
String str = "GST\r";
output.writeUTF(str);
System.out.println("---->");
InputStream input = s.getInputStream();
System.out.println("-----------------> InputStream: "+input.toString());
InputStreamReader reader = new InputStreamReader(input);
System.out.println("-----------------> InputStream: "+reader.toString());
int character;
StringBuilder data = new StringBuilder();
System.out.println(reader.read());
while ((character = reader.read()) != -1) {
data.append((char) character);
}
System.out.println(data);
s.close();
Related
Because some restrictions, I have to use plain Java sockets to download a file published in a http web site. This is how i am reading the response:
String serverIp = "192....";
int serverPort = 3000;
String url = "/path/to/file";
Socket socket = new Socket(serverIp, serverPort);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String postContent = "content";
writer.write("POST " + url + " HTTP/1.0\r\n");
writer.write("Content-length: " + postContent.length() + "\r\n");
writer.write("\r\n");
writer.write(postContent);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.trim().equals("")) {
//Process header
} else {
break;
}
}
int intChar = -1;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((intChar = reader.read()) >= 0) {
out.write(intChar);
}
byte[] byteArray = out.toByteArray();
File outFile = new File("myfile.zip");
FileOutputStream fileOutputStream = new FileOutputStream(outFile);
fileOutputStream.write(byteArray);
fileOutputStream.close();
Every thing works fine, but the file myfile.zip is saved inconsistent. If I use unzip to uncompress the file, I get the error:
Archive: myfile.zip
error [myfile.zip]: missing 55053 bytes in zipfile
(attempting to process anyway)
error [myfile.zip]: start of central directory not found;
zipfile corrupt.
(please check that you have transferred or created the zipfile in the
appropriate BINARY mode and that you have compiled UnZip properly)
When I use curl to do the http post, myfile.zip download consistent and I can open it.
Any light?
Thanks guys. I used the suggestion of
President James K. Polk to write the following solution:
String serverIp = "192....";
int serverPort = 3000;
String url = "/path/to/file";
Socket socket = new Socket(serverIp, serverPort);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String postContent = "content";
writer.write("POST " + url + " HTTP/1.0\r\n");
writer.write("Content-length: " + postContent.length() + "\r\n");
writer.write("\r\n");
writer.write(postContent);
writer.flush();
DataInputStream reader = new DataInputStream(socket.getInputStream());
int c = -1;
StringBuilder header = new StringBuilder();
while ((c = reader.read()) >= 0) {
header.append((char) c);
if (header.length() > 4 && header.substring(header.length() - 4).equals("\r\n\r\n")) {
break;
}
}
File outFile = new File("myfile.zip");
FileOutputStream fileOutputStream = new FileOutputStream(outFile);
while ((c = reader.read()) >= 0) {
fileOutputStream.write(c);
}
reader.close();
fileOutputStream.close();
I am trying to pass message from server to client in terminal. What I would like the program to do is, in the client, it should be able to enter a command, get response from server, and be able to enter another command without restarting Client (by java Client).
Client.java
Socket socket = new Socket(host, port);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String response = "";
boolean continuation = true;
while(continuation) {
Scanner input = new Scanner(System.in);
String command = (input.nextLine()).toString();
bw.write(command+"\r\n");
bw.flush();
if(command.equals("cmd1") {
while ((response = br.readLine()) != null) {
System.out.println(response);
}
}
System.out.println("This line will not execute as well.");
}
Server.java
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String[] in = br.readLine().split("\\s+");
String command = in[0];
if(command.equals("cmd1")) {
String response = "";
response = response + "RESPONSE:\r\n";
response = response + "This is a response.\r\n";
bw.write(response);
bw.flush();
}
If I don't put while((response = br.readLine()!= null) { ... } in Client.java, it is possible to enter multiple inputs in the terminal, but if I put it, it prints the response from the server and another input cannot be done without restarting Client.
Any help would be appreciated.
Thanks
This should work:
server:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
boolean continuation = true;
while (continuation) {
String command = dis.readUTF();
//proceeed command
dos.writeUTF("response");
dos.flush();
}
Client:
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF("your command");
while (dis.available() == 0) {
try {
//wait for response
Thread.sleep(1);
} catch (InterruptedException ex) {
Logger.getLogger(RandomTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
String response = dis.readUTF();
//and so on
Can anybody help me with this here. I am a newbie and I am working on a network application where I have to create a socket connection to the IP address and port that they already given me and then send XML message to the socket and finally include the ReadMe.txt file where I will save what I have received from the server. Here's my code
private static Socket socket;
public static void main(String args[])
{
try
{
socket = new Socket( "196.37.22.179", 9011);
//Send the message to the server
//PrintStream outstrm = null;
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
String str;
str = "<request>";
str += "<EventType>Authentication</EventType>";
str += "<event>";
str += "<UserPin>12345</UserPin>";
str += "<DeviceId>12345</DeviceId>";
str += "<DeviceSer>ABCDE</DeviceSer>";
str += "<DeviceVer>ABCDE</DeviceVer>";
str += "<TransType>Users</TransType>";
str += "</event></request>";
bw.write(str);
bw.flush();
System.out.println("Message sent to the server......! ");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
You can use this code to store results from server in file
//Get the return message from the server
InputStream is = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("ReadMe.txt"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
This question already has answers here:
How do I send file name with file using sockets in Java? [duplicate]
(3 answers)
Closed 6 years ago.
I am able to send Files through socket and receive on other ends . Now i want to send even file name so that after receiving file and saving file from socket i can save the name of file. What to add in client to send filename and in server to receive filename thanks in advance to all
Client.java
try {
clientSocket = new Socket(targetIP, port);
os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
signalActivity("About to start handshake");
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(fileToSend);
BufferedInputStream bis = new BufferedInputStream(fis);
// long BytesToSend = fileToSend.length();
while(true)
{
int bytesRead = bis.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
//BytesToSend = BytesToSend - bytesRead;
os.write(buffer,0, bytesRead);
os.flush();
}
fis.close();
bis.close();
br.close();
isr.close();
is.close();
pw.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
catch(Exception e)
{
}
Server.java
try {
welcomeSocket = new ServerSocket(port);
while(true && serviceEnabled)
{
socket = welcomeSocket.accept();
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String inputData = "";
// String savedAs = "WDFL_File_" + System.currentTimeMillis();
//save the original name and extention
File file = new File(saveLocation, savedAs);
byte[] buffer = new byte[4096];
int bytesRead;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while(true)
{
bytesRead = is.read(buffer, 0, buffer.length);
if(bytesRead == -1)
{
break;
}
bos.write(buffer, 0, bytesRead);
bos.flush();
}
bos.close();
socket.close();
//Start writing to file
}
} catch (IOException e) {
}
catch(Exception e)
{
}
Your client should send the file name first. After that the contents of the file.
The server should read the file name first so the following content of the file can be saved under the same file name.
My client can send Images normally to server, but when it comes to text files they arrive empty. Any ideas what am I doing wrong? I'd really appreciate help, because I have been trying to make this work for many days now. Thanks.
Here is the server code:
class TheServer {
public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();
InputStream is = connection.getInputStream();
int bufferSize = connection.getReceiveBufferSize();
FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();
}
}
and here is the client code:
public class TheClient {
public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 1991);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.newLine();
wr.flush();
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
You are prematurely closing BufferedReader on server side before reading all the data. This essentially closes the connection.
You should not use Reader or Writer for non-character streams like binary image data. And you should not mix BufferedReader with any other stream wrapper for the same stream since it may read as many data as it fills in buffer.