Hi,
I am facing a strange problem. Any help would be apreciated.
What I am trying to do :
----------------------
Transfer a datafile(ascii) from a client to a server using TCP sockets.
My Problem :
----------
The file contents & size varies at the server end after the transfer is complete. This happens when the server is run on a different PC, however if the client and the server are run on the same PC (localhost) this does not happen.
The Client Code:
------------------
import java.net.*;
import java.io.*;
public class tcpClient {
public static void main(
String[] args) {
int port = 1500;
// String server = "10.172.30.33"; // this is anothe PC
String server = "localhost";
Socket socket = null;
int ERROR = 1;
// connect to server
try {
socket = new Socket(server, port);
System.out.println("Connected with server "+socket.getInetAddress()+":"+socket.getPort());
}
catch (UnknownHostException e) {
System.out.println(e);
System.exit(ERROR);
}
catch (IOException e) {
System.out.println(e);
System.exit(ERROR);
}
try {
byte[] buf = new byte[1024];
OutputStream os = socket.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(os,1024);
// I am hardcoding the file name, for
test purpose
String file = "C://source_code.sql";
FileInputStream in = new FileInputStream(file);
int i;
int bytecount=1024;
while ((i = in.read(buf,0,1024)) != -1) {
bytecount=bytecount+1024;
out.write(buf,0,1024);
out.flush();
}
in.close();
out.close();
System.out.println("Bytes Sent :"+bytecount);
}
catch (IOException e) {
System.out.println(e);
}
try {
socket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}
The Server code:
-----------------
import java.net.*;
import java.io.*;
public class tcpServer {
public static void main(String args[]) {
int port;
ServerSocket server_socket;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
System.out.println("port = 1500 (default)");
port = 1500;
}
try {
server_socket = new ServerSocket(port);
System.out.println("Server waiting for client on port " + server_socket.getLocalPort());
// server infinite loop
while(true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());
try {
byte[] b = new byte[1024];
int len=0;
int bytcount=1024;
String FileName="C://ftptest.txt";
FileOutputStream inFile = new FileOutputStream(FileName);
InputStream is = socket.getInputStream();
BufferedInputStream in2 = new BufferedInputStream(is,1024);
while( (len = in2.read(b,0,1024)) != -1 ) {
bytcount=bytcount+1024;
inFile.write(b,0,1024);
}
in2.close();
inFile.close();
System.out.println("Bytes Writen : "+bytcount);
}
catch(IOException e) {
System.out.println("Unable to open file" + e);
return;
}
try {
socket.close();
System.out.println("Connection closed by client");
}
catch (IOException e) {
System.out.println(e);
}
}
}
catch (IOException e) {
System.out.println(e);
}
}
}