Hi I want to implement a program where
client sends a file to server and server displays the message from the file.

I have attatched my java files for reference

Dani AI

Generated

Short correction and a concrete approach: a TCP socket can absolutely carry a file — FTP is just an application protocol implemented on sockets. is incorrect here and is right to object. For the simplest reliable pattern is: client opens the file, sends a small header (filename and length), then streams the raw bytes. The server reads the header, streams the incoming bytes to disk (or into memory for small files), then decodes the saved bytes as text to display.

Example (minimal, single-connection flow):

/* Server side */
ServerSocket ss = new ServerSocket(12345);
try (Socket s = ss.accept();
     DataInputStream in = new DataInputStream(s.getInputStream())) {
  String name = in.readUTF();
  long len = in.readLong();
  try (FileOutputStream fos = new FileOutputStream("received_" + name)) {
    byte[] buf = new byte[4096];
    long rem = len;
    while (rem > 0) {
      int r = in.read(buf, 0, (int)Math.min(buf.length, rem));
      if (r < 0) break;
      fos.write(buf, 0, r);
      rem -= r;
    }
  }
  String text = new String(Files.readAllBytes(Paths.get("received_" + name)), StandardCharsets.UTF_8);
  System.out.println(text);
}
/* Client side */
try (Socket s = new Socket("server.host", 12345);
     DataOutputStream out = new DataOutputStream(s.getOutputStream());
     FileInputStream fis = new FileInputStream("message.txt")) {
  File f = new File("message.txt");
  out.writeUTF(f.getName());
  out.writeLong(f.length());
  byte[] buf = new byte[4096];
  int r;
  while ((r = fis.read(buf)) != -1) out.write(buf, 0, r);
  out.flush();
}

Practical tips: run the server before connecting the client; use try-with-resources and handle IOExceptions; stream data (do not load large files wholly into memory); always send a length or use a framing protocol so the receiver knows where the file ends; handle character encoding explicitly when printing text (e.g., UTF-8). For multiple concurrent clients accept sockets in a loop and hand each to a worker thread or executor. For background reading on sockets in Java see the Java Sockets Tutorial.

Recommended Answers

All 3 Replies

no, we're not going to open attachments. And we're not going to do your homework for you either.
We also can't guess at what your question in, as you're not asking any.

Use FTP rather, you cannot send a file over a socket.

... you cannot send a file over a socket.

Since when? How do you think FTP does it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.