File server and client

In this chapter you will learn:

  1. Transfer a file via Socket

Transfer a file via Socket

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/*from   j a  v  a  2s  .co m*/
public class Main {
  public static void main(String[] args) throws IOException {
    ServerSocket servsock = new ServerSocket(123456);
    File myFile = new File("s.pdf");
    while (true) {
      Socket sock = servsock.accept();
      byte[] mybytearray = new byte[(int) myFile.length()];
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myFile));
      bis.read(mybytearray, 0, mybytearray.length);
      OutputStream os = sock.getOutputStream();
      os.write(mybytearray, 0, mybytearray.length);
      os.flush();
      sock.close();
    }
  }
}

The client module

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
/*from java2s. c  om*/
public class Main {
  public static void main(String[] argv) throws Exception {
    Socket sock = new Socket("127.0.0.1", 123456);
    byte[] mybytearray = new byte[1024];
    InputStream is = sock.getInputStream();
    FileOutputStream fos = new FileOutputStream("s.pdf");
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
    bos.write(mybytearray, 0, bytesRead);
    bos.close();
    sock.close();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. Thread based ServerSocket
  2. A multithreaded Socket Server
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies