I know i have to use InputStream and OutputStream, but i don't know how to do it properly.
So far i think i've managed to do the client part. i read the content of a file, "hi.txt", and i send it to the server.
The problem is in the server part, i do not know how to write the file in the server. Thanks in advance for your help
Here is my code for the client.
Expand|Select|Wrap|Line Numbers
- import java.net.*;
- import java.io.*;
- public class client
- {
- public static void main(String arg[]) throws IOException
- {
- InetAddress addr = InetAddress.getByName(null);//because i'm in my pc
- System.out.println("addr = " + addr);
- Socket socket = new Socket(addr, server.port);
- String source = "c:/hi.txt";
- byte[] buf = new byte[10];//1 kilobyte buffer
- int lentgth;
- InputStream in = new BufferedInputStream(new FileInputStream(source));
- OutputStream out = new BufferedOutputStream(socket.getOutputStream());
- try
- {
- while((lentgth = in.read(buf))>0)
- {
- out.write(buf,0,lentgth);//byte flow sent to the server
- }
- }
- finally
- {
- out.flush();
- out.close();
- in.close();
- System.out.println("closing socket...");
- socket.close();
- }
- }
- }
Server code
Expand|Select|Wrap|Line Numbers
- import java.net.*;
- import java.io.*;
- public class server
- {
- public static final int port = 8080;
- public static void main(String arg[]) throws IOException
- {
- ServerSocket s = new ServerSocket(port);
- System.out.println("Started: " + s);
- byte[] buffer = new byte[10];
- try
- {
- Socket socket = s.accept();
- System.out.println("Connection accepted: "+ socket);
- //copy file code here
- try
- {
- InputStream in = new BufferedInputStream(socket.getInputStream());
- while(true)// loop to copy the file
- {
- }
- }
- finally
- {
- socket.close();
- System.out.println("closing socket...");
- }
- }
- finally
- {
- s.close();
- System.out.println("closing Server socket...");
- }
- }
- }