Transferring Over Network
Hello every one
This is my first participation ,Im new in java , I have question , How I can send a file over network in a client- server paradigm , server send and client receive . the following is trying code
//The client code Client.java:
import java.net.*;
import java.io.*;
public class Client {
ObjectInputStream Sinput;
ObjectOutputStream Soutput;
Socket socket;
Client(int port) {
try {
socket = new Socket("localhost", port);
FileInputStream test=new FileInputStream("file name");
Soutput.writeObject(test);
Soutput.flush();
}
catch(Exception e) {
System.out.println("Error connectiong to server:" + e);
return;
}
try{
Sinput.close();
Soutput.close();
}
catch(Exception e) {}
}
public static void main(String[] arg) {
new Client(1500);
}
}
//The server code Server.java:
import java.io.*;
import java.net.*;
/
public class Server {
private ServerSocket serverSocket;
Server(int port) {
try
{
serverSocket = new ServerSocket(port);
System.out.println("Server waiting for client on port " + serverSocket.getLocalPort());
while(true)
{
Socket socket = serverSocket.accept();
System.out.println("New client asked for a connection");
TcpThread t = new TcpThread(socket);
System.out.println("Starting a thread for a new Client");
t.start();
}
}
catch (IOException e) {
System.out.println("Exception on new ServerSocket: " + e);
}
}
public static void main(String[] arg) {
new Server(1500);
}
class TcpThread extends Thread implements Serializable {
Socket socket;
ObjectInputStream Sinput;
ObjectOutputStream Soutput;
TcpThread(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.println("Thread trying to create Object Input/Output Streams");
try
{
Soutput = new ObjectOutputStream(socket.getOutputStream());
Soutput.flush();
}
catch (IOException e) {
System.out.println("Exception creating new Input/output Streams: " + e);
return;
}
System.out.println("Thread waiting for a String from the Client");
try {
byte[] msgArray=null;
File file = (File)Sinput.readObject();
FileInputStream fisSrc=new FileInputStream(file);
FileOutputStream fosDes=new FileOutputStream("ClientRceivedTempFile");
int n;
while ((n = fisSrc.available()) > 0) {
byte[] b = new byte[n];
int result = fisSrc.read(b);
if (result == -1) break;
fosDes.write( b );}
fisSrc.close();
fosDes.close();
}
catch (IOException e) {
System.out.println("Exception reading/writing Streams: " + e);
return;
}
catch (ClassNotFoundException o) {
}
finally {
try {
Soutput.close();
Sinput.close();
}
catch (Exception e) {
}
}
}
}
}
Im lost:o help me please :confused:Im appreciate your help :p