No value is writtern in my tcp client/server program - java

In my TCP socket program I have to send data from client to server. In server side I have to read the streams and write it in file. But File is created and nothing is written inside.
Client side coding to send file:
try
{
Socket ss = new Socket("localhost", 5010);
BufferedOutputStream put = new BufferedOutputStream(ss.getOutputStream());
BufferedReader st = new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f = new File("e://read.txt");
FileInputStream fis = new FileInputStream(f);
byte buf[] = new byte[1024];
int read;
while((read = fis.read(buf, 0, 1024)) != -1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
Server to read the inputstream and write it in a file:
try
{
ServerSocket ss = new ServerSocket(5010);
Socket s = ss.accept();
BufferedReader get = new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata = new FileWriter("c://write.txt");
BufferedWriter bw = new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
}
catch(Exception e)
{
System.out.println(e);
}
What is the problem?

You forgot bw.close and bw.flush....below is the code that works...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(5010);
Socket s=ss.accept();
BufferedReader get= new BufferedReader(new InputStreamReader(s.getInputStream()));
FileWriter writedata=new FileWriter("c://Test//testoutput.txt");
BufferedWriter bw=new BufferedWriter(writedata);
String line=bw.toString();
while ((line = get.readLine()) != null) {
bw.write(line + "\n");
}
bw.flush();
bw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class TestClient
{
public static void main(String[] args)
{
try
{
Socket ss=new Socket("localhost",5010);
BufferedOutputStream put=new BufferedOutputStream(ss.getOutputStream());
BufferedReader st=new BufferedReader(new InputStreamReader(ss.getInputStream()));
File f=new File("c://Test//testinput.txt");
FileInputStream fis=new FileInputStream(f);
byte buf[]=new byte[1024];
int read;
while((read=fis.read(buf,0,1024))!=-1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
ss.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Don't use Readers and Writers unless you know that the data is text. Use InputStreams and OutputStreams, and copy them so:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
in.close();
Use this logic in both the client and the server.
Notes:
It is counterproductive to put a flush() inside that loop.
If buffer is greater than 4096, which it should be, it is pointless to use a BufferedInputStream.

Related

Java: Multi line output via Socket

i got some struggle with my code. I have to send some commands via client to a server (create a file or list files in the directory) the server should create the files or send a list of existing files back to the client. It worked, but i guess the while loop for output on client side never stops and the client cant input new commands. I dont get the problem :(. Many thanks in advance.
Server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.File;
import java.io.FileWriter;
public class MyServer {
private final static String DIRECTORYLISTING = "directoryListing";
private final static String ADDFILE = "addFile";
private static String path = "/home/christoph/eclipse-workspace/Distributed Systems Ex 01/Work_Folder";
private static PrintWriter pw = null;
private static File file = null;
private static String command1 = null; // Command
private static String command2 = null; // File name
private static String command3 = null; // File content
private static ArrayList<File> files = new ArrayList<>(); //
public static void splitClientInput(String clientInput) {
try {
String [] splittedInput = clientInput.split(";");
command1=splittedInput[0];
command2=splittedInput[1];
command3=splittedInput[2];
} catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
public static void directoryListing() {
try {
File[] s = file.listFiles();
for(int i = 0; i<s.length;i++) {
pw.println(s[i].getName());
}
pw.flush();
}catch(NullPointerException e) {
e.printStackTrace();
}
}
public static void addFile(String command2,String command3) throws IOException {
file = new File(path +"/" +command2);
if(file.isFile()) {
pw.println("This Filename "+command2+" already exists.");
} else {
try {
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(command3);
files.add(file);
pw.println(file.getName()+" created");
if(command3.equals(null)) {
pw.println("Your created file is empty");
}
fileWriter.close();
}catch(IOException e) {
pw.println("Error by creating file");
}catch (NullPointerException e) {
pw.println("Your created file is empty");
}
}
}
public static void checkInputCommand(String command1, String command2, String command3) throws IOException {
switch(command1) {
case DIRECTORYLISTING:
directoryListing();
break;
case ADDFILE:
addFile(command2, command3);
break;
}
}
public static void main(String[] args) {
try {
file = new File(path);
files = new ArrayList<File>(Arrays.asList(file.listFiles()));
ServerSocket ss = new ServerSocket(1118);
System.out.println("Server Started...");
Socket socket = ss.accept();
OutputStream os = socket.getOutputStream();
pw=new PrintWriter(os);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String clientInput = null;
while((clientInput = br.readLine()) != null) {
splitClientInput(clientInput);
checkInputCommand(command1, command2, command3);
pw.flush();
}
pw.flush();
br.close();
isr.close();
is.close();
pw.close();
os.close();
socket.close();
ss.close();
System.out.println("Server closed");
}catch(BindException e) {
e.printStackTrace();
}catch(SocketException e) {
e.printStackTrace();
}catch(java.lang.NullPointerException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MyClient {
public static void main(String[] args) throws Exception{
try {
Scanner sc = new Scanner(System.in);
Socket s = new Socket("127.0.0.1", 1118);
System.out.println("Client started");
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os);
String str= null;
while(true){
System.out.print("Client input: ");
pw.println(sc.nextLine());
pw.flush();
// System.out.println(br.readLine());
/*
* dont get out of the loop?
*/
while((str=br.readLine())!=null) {
System.out.println(str);
}
br.close();
isr.close();
is.close();
s.close();
}
} catch(NullPointerException e) {
e.printStackTrace();
} catch(ConnectException e) {
e.printStackTrace();
}catch(UnknownHostException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Java Client Server chatting program

I got a code from the internet for a Client and Server to communicate in java. I modified it a bit, so that the server and client are able to chat to each other.
Initially my client sends a message to server, then server to client, then client to server and it goes on...(one cannot send more than one message continuously to the other). For this there is a basic code put in the while loop so that the conversation goes on 1 to 1. But as i put the while loop, the message from server is not received by client. If there is no while loop(which i have commented in the code here), then first the message is sent by client to server and then server to client and the program stops.
Please help me in making the chat go endlessly.
//SERVER
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static Socket socket;
public static void main(String[] args)
{
try
{
int port = 25000;
ServerSocket serverSocket = new ServerSocket(port);
socket = serverSocket.accept();
System.out.println("Server Started and listening to the port 25000");
//while(true){
//Server is running always. This is done using this while(true) loop
//Reading the message from the client
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String number = br.readLine();
System.out.println("Received from client: "+number+"\n");
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
//Sending the response back to the client.
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(s);
bw.flush();
System.out.println("Sent (to " + socket + ") client: "+s+"\n");
//String abc = bufferRead.readLine();
//System.out.println("SAA");
//}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e){}
}
}
}
//CLIENT
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
public class Client {
private static Socket socket;
public static void main(String args[])
{
try
{
String host = "localhost";
int port = 25000;
InetAddress address = InetAddress.getByName(host);
socket = new Socket(address, port);
//while(true){
//Send the message to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
String sendMessage = s + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Sent to server: " +sendMessage+"\n");
//Get the return message from the server
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
System.out.println(socket);
String message = br.readLine();
System.out.println("Received from server: "+message+"\n");
//}
}
catch (Exception exception)
{
exception.printStackTrace();
}
finally
{
//Closing the socket
try
{
socket.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Server.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Server implements Runnable {
ServerSocket serversocket;
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in="",out="";
public Server() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
serversocket = new ServerSocket(5000);
System.out.println("Server is waiting. . . . ");
socket = serversocket.accept();
System.out.println("Client connected with Ip " + socket.getInetAddress().getHostAddress());
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t1) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Client says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
Client.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
public class Client implements Runnable {
BufferedReader br1, br2;
PrintWriter pr1;
Socket socket;
Thread t1, t2;
String in = "", out = "";
public Client() {
try {
t1 = new Thread(this);
t2 = new Thread(this);
socket = new Socket("localhost", 5000);
t1.start();;
t2.start();
} catch (Exception e) {
}
}
public void run() {
try {
if (Thread.currentThread() == t2) {
do {
br1 = new BufferedReader(new InputStreamReader(System.in));
pr1 = new PrintWriter(socket.getOutputStream(), true);
in = br1.readLine();
pr1.println(in);
} while (!in.equals("END"));
} else {
do {
br2 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = br2.readLine();
System.out.println("Server says : : : " + out);
} while (!out.equals("END"));
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Client();
}
}
//server.java
import java.io.*;
import java.net.*;
public class server {
public static void main(String []V){
try{
ServerSocket ss = new ServerSocket(1201);
Socket s = ss.accept();
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgIn = Din.readUTF();
System.out.println(MsgIn);
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
Dout.flush();
}
s.close();
}catch(Exception e){
}
}
}
//clients.java
import java.io.*;
import java.net.*;
import javax.xml.crypto.Data;
public class clients {
public static void main(String []S){
try{
Socket s = new Socket("192.168.0.103",1201);//my pc's ip
//Socket s = new Socket("192.168.0.100",1201);
DataInputStream Din = new DataInputStream(s.getInputStream());
DataOutputStream Dout = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String MsgIn="",MsgOut="";
while(!MsgIn.equals("end")){
MsgOut = br.readLine();
Dout.writeUTF(MsgOut);
MsgIn = Din.readUTF();
System.out.println(MsgIn);
}
}catch(Exception e){
}
}
}
import java.io.*;
import java.net.*;
class serversvi1
{
public static void main(String svi[])throws IOException
{
try
{
ServerSocket servsock=new ServerSocket(5510);
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
System.out.println(fil+" :is file transfer");
File myfile=new File(fil);
while(true)
{
Socket sock=servsock.accept();
byte[] mybytearray=new byte[(int)myfile.length()];
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybytearray,0,mybytearray.length);
OutputStream os=sock.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}
}
catch(Exception saranvi)
{
System.out.print(saranvi);
}
}
}
import java.io.*;
import java.net.*;
class clientsvi1
{
public static void main(String svi[])throws IOException
{
try
{
Socket sock=new Socket("localhost",5510);
byte[] bytearray=new byte[1024];
InputStream is=sock.getInputStream();
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter the file name");
String fil=dis.readLine();
FileOutputStream fos=new FileOutputStream(fil);
BufferedOutputStream bos=new BufferedOutputStream(fos);
int bytesread=is.read(bytearray,0,bytearray.length);
bos.write(bytearray,0,bytesread);
System.out.println("out.txt file is received");
bos.close();
sock.close();
}
catch(Exception SVI)
{
System.out.print(SVI);
}
}
}

transfer String and file through socket

i would like to transfer file from server to client. before that i want to send file names from specific directory. the file is not transferring as the read is returning -1. can any one correct me where i am going wrong?
My client code goes like this.
import java.io.*;
import java.net.*;
class PC1Client {
public static void main(String args[]) throws UnknownHostException, IOException
{
byte[] aByte = new byte[1];
int bytesRead;
Socket sock = new Socket("localhost",3000);
InputStream is1 = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
String st = br.readLine();
System.out.println(st);
InputStream is = sock.getInputStream();
FileOutputStream fos = null;
fos = new FileOutputStream("F:\\ANI1.TXT");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
System.out.println(bytesRead);
do {
System.out.println("s");
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
sock.close();
}
}
My server code goes like this.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class PC1Server {
public static void main(String[] args) throws IOException
{
ServerSocket serversocket = new ServerSocket(3000);
try
{
while(true)
{
String str="";
Socket socket = serversocket.accept();
File file = new File("D:\\ani");
for(File fi : file.listFiles() )
{
str=str+fi.getName()+";";
}
PrintWriter outname = new PrintWriter(socket.getOutputStream());
outname.println(str);
outname.flush();
outname.close();
System.out.println("hello der");
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream() );
File myfile = new File("d:/hello.txt");
byte[] mybyte = new byte[(int)myfile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myfile));
bis.read(mybyte, 0, mybyte.length);
out.write(mybyte, 0, mybyte.length);
out.flush();
out.close();
}
}
catch(Exception e)
{
}
}
}
Few notes:
byte[] aByte = new byte[1]; is pointless - it forces you to read the file 1 byte at a time.
InputStream is = sock.getInputStream(); what is the point of opening the same input stream second time?
outname.close(); in your server code is what causes your problem.
Why do you close your output stream just to reopen it again?

Java: Bytes are not transferred correctly

I've made a server that should let the client udpate a file. All in all it is working, but some bytes, for example HEX 9D is getting to HEX 3F. I have no more ideas and didn't find anything on the web. My server code:
package de;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class UpdateThread extends Thread {
public UpdateThread(Socket s) {
socket = s;
}
public void run() {
try {
execute();
} catch (IOException e) {
e.printStackTrace();
}
}
#SuppressWarnings("resource")
public void execute() throws IOException {
if (UpdateProvider.update) {
int i = 0;
SocketTools.sendData(1, socket);
File file = new File("." + System.getProperty("file.separator").toString() + "update_package.jar");
OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
FileReader reader = new FileReader(file);
while ((i = reader.read()) != -1) {
writer.write(i);
}
writer.flush();
writer.close();
} else {
SocketTools.sendData(0, socket);
}
}
private Socket socket;
}
And my client code:
package de;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Main {
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 16642);
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
//InputStreamReader reader = new InputStreamReader(s.getInputStream());
int i = 0;
FileWriter writer = new FileWriter(new File("C:\\update_package.jar"));
int state = reader.read();
if (state == 48) {
System.exit(0);
}
if (state == 49) {
while ((i = reader.read()) != -1) {
System.out.println(i);
writer.write(i);
}
System.out.println("ENDE");
writer.flush();
}
}
}
You're not specifying a proper encoding for the transmission (you should use InputStream/OutputStreams instead of Reader/Writer for this anyways, since you're handling binary data and not text). 0x3F is the questionmark '?', meaning that a non-ASCII character (128 or higher) has been converted.
So lose the Readers and Writers and go with Streams.
Encoding is needed for text files only. I looked at your source code. You are trasferring a jar, which is a binary file, not text. If you use use text processing classes for binary data, you can get a lot of unpredictable transformations. Don't use OutputStreamWriter. Use socket.getOutputStream() directly:
OutputStream = socket.getOutputStream();
...
out.write(...);
Same for client. Don't use InputStreamReader. Use s.getInputStream() directly:
InputStream in = s.getInputStream();
...
in.read(...);

File Transfer from Server to Client using java sockets. Error on Server side and File transferred to client is empty

I have a Client and Server, where in client enters the filename, that filename will be checked on server side under pre-defined path, if the file exists, it will be transferred to client side under a similar pre-defined path. I have two problems :
1) In Server, i am not able to compare the file under given pre-defined path, as it is showing FileNotFoundException (no such file/dir).
2) Even following the above exception, the file is transferred and it is empty.
Here are my Client and Server:
Client:
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2client
{
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8085);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e)
{
System.exit(0);
}
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
String str = "/home/user/";
FileOutputStream fs=new FileOutputStream(new File(str,f1.toString()));
while((u=get.readLine())!=null)
{
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8085);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
String str = "/home/user/Desktop/";
String path = str + s;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+s);
File f=new File(path);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
See with binary data you have change the readers as they are capable of only characters and do not work with byte stream. moreover readline means read till end of line and in binary files ('\n') does not make too much sense.
This is from documentation of printWriter
It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
What you would want now is to use byte arrays and write them as chunks like this :
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8085);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
BufferedOutputStream put=new BufferedOutputStream(cs.getOutputStream());
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
String str = "/home/milind/Desktop/";
String path = str + s;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+s);
File f=new File(path);
if(f.isFile())
{
FileInputStream fis=new FileInputStream(f);
byte []buf=new byte[1024];
int read;
while((read=fis.read(buf,0,1024))!=-1)
{
put.write(buf,0,read);
put.flush();
}
//d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
The client
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2client
{
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedInputStream get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8085);
get=new BufferedInputStream(s.getInputStream());
put=new PrintWriter(s.getOutputStream(),true);
String f;
int u;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
String str = "/home/milind/";
FileOutputStream fs=new FileOutputStream(new File(str,f1.toString()));
byte jj[]=new byte[1024];
while((u=get.read(jj,0,1024))!=-1)
{
fs.write(jj,0,u);
}
fs.close();
System.out.println("File received");
s.close();
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
Few things are for sure when you are dealing with the socket.
If at the other end you are reading line like get.readLine(); then from the sender program should have write into socket like this put.writeBytes("any string variable"+"\n") or put.println("some string variable or literal.")
you are reading like get.readLine() and you are writing the bytes whatever you are reading from the direct file.
This is my example how I do read,write on the socket when I need pure text to transfer in bytes.
Server {
...
soc = echoServer.accept();
out = new DataOutputStream(soc.getOutputStream());
out.flush();
in = new DataInputStream(soc.getInputStream());
out.writeBytes("some text in here \n");
out.flush();
...
}
Client{
...
soc = new Socket("10.210.13.121", 62436);
out = new DataOutputStream(soc.getOutputStream());
out.flush();
in = new DataInputStream(soc.getInputStream());
...
while(true)
if(in.available() > 0)
String str = in.readLine();
...
}
Please use f.isFile() instead of f.exisits. It is a known issue.
In server you mistakenly wrote
BufferedReader d=new BufferedReader(new FileReader(s));
instead of
BufferedReader d=new BufferedReader(new FileReader(f));
Fixed codes
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2server
{
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{
ss=new ServerSocket(8085);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
String str = "/home/milind/Desktop/";
String path = str + s;
System.out.println("The requested file is path: "+path);
System.out.println("The requested file is : "+s);
File f=new File(path);
if(f.isFile())
{
BufferedReader d=new BufferedReader(new FileReader(f));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}
Other one
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2client
{
public static void main(String srgs[])throws IOException
{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8085);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
String str = "/home/milind/";
FileOutputStream fs=new FileOutputStream(new File(str,f1.toString()));
while((u=get.readLine())!=null)
{
System.out.println(u);
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}catch(Exception e)
{
e.printStackTrace();
System.exit(0);
}
}
}
Don't use Readers and Writers unless you know that the contents are characters. If you don't, use InputStreams and OutputStreams. In this case a ZIP file is certainly binary, not character data, so you are bound to corrupt it by using Readers and Writers.

Categories

Resources