I have written the following code for sending a text file from Client to Server using Sockets. I am new to both JAVA and Socket Programming. I feel I have got the socket concepts but Java Streams are quite confusing. Any help with the following code will be really helpful. PLEASE mention the mistake and Solution with reasoning.
The data seems to be sent just fine. But it is not received on the other end.
Server Code:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(3000);
while(true)
{
Socket convSocket = serverSocket.accept();
System.out.println("connection accepted");
BufferedReader in = new BufferedReader(new InputStreamReader(convSocket.getInputStream()));
FileWriter fileOut = new FileWriter("/Users/aakashmalhotra/a.txt");
int c;
while( (c = in.read()) != -1){
fileOut.write(c);
}
System.out.println("Transfer Done");
}
}
}
Client Code:
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] argv) throws Exception {
Socket clientSocket = new Socket("localhost", 3000); // create a socket
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedReader fileIn = new BufferedReader(new FileReader("/Users/aakashmalhotra/s.txt"));
int c;
while ((c = fileIn.read()) != -1) {
out.write(c);
}
}
}
throws Exceptionwhile not the cause of your problems, just shouldn't be done. In the least, catch exceptions and print stacktraces.