Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement TCP server and TCP client in java to transfer files

Tags:

java

tcp

client

I have implement the simple TCP server and TCP client classes which can send the message from client to server and the message will be converted to upper case on the server side, but how can I achieve transfer files from server to client and upload files from client to server. the following codes are what I have got.

TCPClient.java:

import java.io.*;
import java.net.*;

class TCPClient {
 public static void main(String args[]) throws Exception {
        String sentence;
        String modifiedSentence;
        BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
        Socket clientSocket = new Socket("127.0.0.1", 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + "\n");
        modifiedSentence = inFromServer.readLine();
        System.out.println("FROM SERVER:" + modifiedSentence);
        clientSocket.close();
    }
}

TCPServer.java:

import java.io.*;
import java.net.*;

class TCPServer {
    public static void main(String args[]) throws Exception {
        int firsttime = 1;
        while (true) {
            String clientSentence;
            String capitalizedSentence="";
            ServerSocket welcomeSocket = new ServerSocket(3248);
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();
            //System.out.println(clientSentence);
            if (clientSentence.equals("set")) {
                outToClient.writeBytes("connection is ");
                System.out.println("running here");
                //welcomeSocket.close();
                //outToClient.writeBytes(capitalizedSentence);
            }
            capitalizedSentence = clientSentence.toUpperCase() + "\n";
            //if(!clientSentence.equals("quit"))
            outToClient.writeBytes(capitalizedSentence+"enter the message or command: ");
            System.out.println("passed");
            //outToClient.writeBytes("enter the message or command: ");
            welcomeSocket.close();
            System.out.println("connection terminated");
        }
    }
}

So, the TCPServer.java will be executed first, and then execute the TCPClient.java, and I try to use the if clause in the TCPServer.java to test what is user's input,now I really want to implement how to transfer files from both side(download and upload).Thanks.

like image 286
starcaller Avatar asked Jan 12 '11 07:01

starcaller


People also ask

How do I run a TCP client/server program in Java?

Here, we'll use a very simple client and server example to show the use of TCP socket in Java. The client assumes that the server is listening for connection request on port serverPort via TCP. int serverPort = 4020; InetAddress host = InetAddress. getByName("localhost"); Socket socket = new Socket(host,serverPort);

How would you implement TCP client/server communication?

TCP sockets are used for communication between a server and a client process. The server's code runs first, which opens a port and listens for incoming connection requests from clients. Once a client connects to the same (server) port, the client or server may send a message.

How files are transferred from client to server?

The server sends an acknowledgement, called a SYN ACK, to the client. The client sends another acknowledgement message to the server. After the TCP handshake, the client provides credentials to authenticate the user and server. The file is transferred and available for download.


1 Answers

So lets assume on server side you have received the file name and file path. This code should give you some idea.

SERVER

PrintStream out = new PrintStream(socket.getOutputStream(), true);
FileInputStream requestedfile = new FileInputStream(completeFilePath);
byte[] buffer = new byte[1];
out.println("Content-Length: "+new File(completeFilePath).length()); // for the client to receive file
while((requestedfile.read(buffer)!=-1)){
    out.write(buffer);
    out.flush();    
    out.close();    
}
requestedfile.close();

CLIENT

DataInputStream in = new DataInputStream(socket.getInputStream());
int size = Integer.parseInt(in.readLine().split(": ")[1]);
byte[] item = new byte[size];
for(int i = 0; i < size; i++)
    item[i] = in.readByte();
FileOutputStream requestedfile = new FileOutputStream(new File(fileName));
BufferedOutputStream bos = new BufferedOutputStream(requestedfile);
bos.write(item);
bos.close();
fos.close();
like image 94
Vikrant Goel Avatar answered Sep 20 '22 21:09

Vikrant Goel