i have this code for transferring text files from server to client using sockets.i now want to transfer a video file from the server to client.how can i do that.how do i change my code to include video file?can anyone please help me.
server code
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;
public class SimpleFileServer {
public final static int SOCKET_PORT = 13267; //
public final static String FILE_TO_SEND = "c:/temp/source.pdf";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + "bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
client code
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "c:/temp/source-downloaded.pdf";
public final static int FILE_SIZE = 6022386;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
Related
My program stops on the line:
int file = is.read();
And I don't know why.
-client:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Main {
#SuppressWarnings("resource")
public static void main(String[] args) throws UnknownHostException, IOException {
Socket sock = new Socket("localhost", 5000);
String FileName = "Manik.txt";
File MyFile = new File(FileName);
int FileSize = (int) MyFile.length();
OutputStream os =sock.getOutputStream();
PrintWriter pr = new PrintWriter(sock.getOutputStream(), true);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(MyFile));
Scanner in = new Scanner(sock.getInputStream());
pr.println(FileName);
pr.println(FileSize);
byte[] filebyte = new byte[FileSize];
bis.read(filebyte, 0, filebyte.length);
os.write(filebyte, 0, filebyte.length);
System.out.println(in.nextLine());
os.flush();
sock.close();
}
}
Server:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server
{
public static void main(String[] Args) throws IOException
{
try (ServerSocket servsock = new ServerSocket(5000))
{
Socket sock = servsock.accept();
System.out.println("FFFF");
Scanner in = new Scanner(sock.getInputStream());
InputStream is = sock.getInputStream();
PrintWriter pr = new PrintWriter(sock.getOutputStream(), true);
String FileName = in.nextLine();
int FileSize = in.nextInt();
FileOutputStream fos = new FileOutputStream(FileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] filebyte = new byte[FileSize];
int file = is.read();
bos.write(filebyte, 0, file);
System.out.println("Incoming File: " + FileName);
System.out.println("Size: " + FileSize + "Byte");
if(FileSize == file)System.out.println("File is verified");
else System.out.println("File is corrupted. File Recieved " + file + " Byte");
pr.println("File Recieved SUccessfully.");
bos.close();
sock.close();
}
}
}
I am new to java and I made a chat application through which client and server can send and receive messages, now I was trying to send a file from client to server but after the file is received by server , client and server both cant send messages , Here is the code :
Client Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ClientFrame extends javax.swing.JFrame {
static Socket s;
static DataOutputStream dos1;
static DataInputStream dis;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ClientFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String o = jT.getText() + "\n" + " Client ->" + str1;
jT.setText(o);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//send file
try {
String st = jT.getText() + "\n" + " Client -> " + "Sending a file";
jT.setText(st);
String str1 = "Client Sending a file,Press 'REC File' ";
String st1 = "\n" + " Client ->" + str1;
dos1.writeUTF(st1);
} catch (Exception e) {
}
long length = file.length();
byte[] bytes = new byte[65536];//65536 is max, i think
InputStream in;
try {
in = new FileInputStream(file);
OutputStream out = s.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientFrame().setVisible(true);
}
});
try {
s = new Socket("localhost", 3000);
} catch (Exception e) {
}
s_r_m();
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = (String) dis.readUTF();
String out = jT.getText() + "\n" + " Server ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
Server Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ServerFrame extends javax.swing.JFrame {
static ServerSocket ss;
static Socket s;
static DataInputStream dis;
static DataOutputStream dos1;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ServerFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String out = jT.getText() + "\n" + " Server ->" + str1;
jT.setText(out);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
//rec file
InputStream in = null;
OutputStream out = null;
try {
in = s.getInputStream();
out = new FileOutputStream("F:\\yoMama.exe");
int count;
byte[] buffer = new byte[65536];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
String o = jT.getText() + "\n" + " Client ->" + " File received";
jT.setText(o);
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServerFrame().setVisible(true);
}
});
try {
ss = new ServerSocket(3000);
s = ss.accept();//will accept connection from client,waiting state untill client connects
s_r_m();
} catch (Exception e) {
}
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = dis.readUTF();
String out = jT.getText() + "\n" + " Client ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
The problem is in the s_r_m() function. In while loop first statement is String str = dis.readUTF(); So here both Client and Server will wait for the reply from the other side first which will end up in a Deadlock. So Any of them won't be able to send any data till the receive from the other side.
So there you need to change code accordingly. I have implemented a code to solve this problem which takes input from Key-Board(STDIN).
DataInputStream dis=new DataInputStream(sckt.getInputStream());
DataInputStream dis1=new DataInputStream(System.in);
DataOutputStream dos=new DataOutputStream(sckt.getOutputStream());
String str="";
while(true)
{
while(dis.available()>0) //If input is available from the other side.
{
String out = jT.getText() + "\n" + " Client ->" + dis.readUTF();
jT.setText(out);
}
while(dis1.available()>0) //If input is available from STDIN to send it to the other side.
{
str=sc.nextLine();
dos.writeUTF(str);
dos.flush();
}
}
Here you can change code of taking input from STDIN to Text-Field you have in your application. So Whenever a user press Send Button , It will send the message to the other side.
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
public class FileTransfer {
private Socket socket;
private static final int MAX_BUFFER = 8192;
public FileTransfer(Socket socket) {
this.socket = socket;
}
public boolean sendFile(File file) {
boolean errorOnSave = false;
long length = file.length();
if (file.exists()) {
FileInputStream in = null;
DataOutputStream out = null;
try {
in = new FileInputStream(file);
out = new DataOutputStream(this.socket.getOutputStream());
out.writeLong(length);
out.flush();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
int i=0;
while ((read = in.read(buffer)) != -1) {
System.out.println(i);
i++;
out.write(buffer, 0, read);
out.flush();
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when try send file " + file.getName() + " \nSocket: "
+ socket.getInetAddress() + ":" + socket.getPort() + "\n\t" + e);
errorOnSave = true;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
System.out.println("An error has occurred when closing the InputStream of the file "
+ file.getName() + "\n\t" + e.getMessage());
}
}
}
return !errorOnSave;
} else {
return false;
}
}
public boolean saveFile(File fileSave) {
RandomAccessFile file = null;
DataInputStream in = null;
boolean errorOnSave = false;
try {
file = new RandomAccessFile(fileSave, "rw");
file.getChannel().lock();
in = new DataInputStream(this.socket.getInputStream());
long fileSize = in.readLong();
byte buffer[] = new byte[MAX_BUFFER];
int read = 0;
while ((fileSize > 0) && ((read = in.read(buffer, 0, (int) Math.min(buffer.length, fileSize))) != -1)) {
file.write(buffer, 0, read);
fileSize -= read;
buffer = new byte[MAX_BUFFER];
}
} catch (FileNotFoundException e1) {
System.out.println(e1.getMessage());
return false;
} catch (IOException e) {
System.out.println("An error has occurred when saving the file\n\t" + e.getMessage());
errorOnSave = true;
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println(
"An error occurred when closing the file " + fileSave.getName() + "\n\t" + e.getMessage());
errorOnSave = true;
}
}
if (errorOnSave) {
if (fileSave.exists()) {
fileSave.delete();
}
}
}
return !errorOnSave;
}
}
I have a problem with my java project(its going to send files from server to client...) its always telling me after a few seconds
"Connection reset by peer: socket write error" if someone has the answear please tell whats wrong with my code.....
I had this issue recently: Try this
setBufferSize(1024*1024);
setKeepAlive(false);
Also check if you are on the same WLAN connection (both your device and the server itself)
I hope this helps you get something going!
i am really stuck with a little project i'm doing. I am trying to send music files (only .wav) over a socket from a server to a client. Everything works perfectly fine (i think...) except that the file that is received by the client isn't complete. I can't play the file and I can see that it is a bit smaller than the one the server has. What am I doing not right?
Here is the server code:
private Socket client;
private String filename;
private TBMCAudioServer ac;
private FileInputStream fis;
private BufferedOutputStream out;
int bufferSize = 0;
FileSender(Socket client, String filename, TBMCAudioServer ac){
this.client = client;
this.filename = filename;
this.ac = ac;
}
#Override
public void run(){
ac.ex.sendMessage(client, "[#preload#]" + filename);
File dir = new File(ac.getDataFolder() + File.separator + "music");
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dir, filename + ".wav");
long length = file.length();
if(length > Integer.MAX_VALUE){
logger.info("File is too large.");
}
byte[] bytes = new byte[(int) length];
try{
fis = new FileInputStream(file);
out = new BufferedOutputStream(client.getOutputStream());
} catch (IOException e){
logger.info(e.getMessage());
}
int count;
try {
while((count = fis.read(bytes,0,bytes.length)) != -1){
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
} catch (IOException e) {
logger.info(e.getMessage());
}
}
and here you can see my client code:
private Socket server;
private String filename;
private AudioClient ac;
InputStream is = null;
FileOutputStream fos = null;
int bufferSize = 0;
FileReceiver(Socket server, String filename, AudioClient ac){
this.server = server;
this.filename = filename;
this.ac = ac;
}
#Override
public void run() {
try{
is = server.getInputStream();
bufferSize = server.getReceiveBufferSize();
ac.logConsole("Buffer size: " + bufferSize);
} catch (IOException ex){
ac.logConsole(ex.getMessage());
}
try{
fos = new FileOutputStream(AudioClient.util.getLineValue(3) + filename + ".wav");
} catch (FileNotFoundException e){
ac.logConsole(e.getMessage());
}
byte[] bytes = new byte[bufferSize];
int count;
try {
while((count = is.read(bytes, 0, bytes.length)) != -1){
fos.write(bytes, 0, count);
}
ac.logConsole("yay");
is.close();
fos.flush();
fos.close();
} catch (IOException e) {
ac.logConsole(e.getMessage());
}
}
Okay I managed to send the file fully so I can see it has the same size as where it came from with my new code. The only problem is that i'm sending a music file and I can't play the file that is sent. Maybe someone knows what the problem is?
Server code:
package me.Ciaran.simplefileserver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String FILE_TO_SEND = "D:/server/plugins/TBMCAudioServer/music/DLTALL.wav"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
final File myFile= new File(FILE_TO_SEND); //sdcard/DCIM.JPG
byte[] mybytearray = new byte[8192];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
try {
os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
int read;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
and here is the client code:
package me.Ciaran.simplefileclient;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "127.0.0.1"; // localhost
public final static String
FILE_TO_RECEIVED = "C:/Users/Ciaran/Documents/TESTEN/music/DLTALL.wav"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
InputStream in;
int bufferSize=0;
try {
bufferSize=sock.getReceiveBufferSize();
in=sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream(FILE_TO_RECEIVED);
byte[] buffer = new byte[bufferSize];
int read;
while((read = clientData.read(buffer)) != -1){
output.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
I am trying to write a code that would enable one user to send to or receive from another user. I have written a method to send file called sendFile, it shows that it has sent file but I cannot find where the sent file is saved.
Server side:
package DFT;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerSide {
private static ServerSocket serverSocket = null;
private static Socket clientSocket = null;
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) {
try {
serverSocket = new ServerSocket(2222);
System.out.println("Distributed File Transfer Server has successfully started");
} catch (IOException e) {
System.out.println(e);
}
while (true) {
try {
clientSocket = serverSocket.accept();
int i;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
class clientThread extends Thread {
// private DataInputStream is = null;
private PrintStream os = null;
private BufferedReader is;
// private PrintWriter os;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
private String name, pass;
private int id;
private static final int totalUser = 5;
private static final String username[] = new String[totalUser];
private static final String password[] = new String[totalUser];
private static boolean online[] = new boolean[totalUser];
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
username[0] = "user1";
username[1] = "user2";
username[2] = "user3";
username[3] = "user4";
username[4] = "user5";
password[0] = "123";
password[1] = "456";
password[2] = "789";
password[3] = "012";
password[4] = "345";
maxClientsCount = threads.length;
}
#Override
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
/*
* Create input and output streams for this client.
*/
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintStream(clientSocket.getOutputStream());
if (is.readLine().trim().equals("login")) {
name = is.readLine().trim();
pass = is.readLine().trim();
}
int i, j;
for (i = 0; i < totalUser; i++) {
if (name.equals(username[i]) && pass.equals(password[i])) {
break;
}
}
if (i < totalUser) {
if (online[i]) {
os.println("This user already logged in");
threads[i] = null;
is.close();
os.close();
clientSocket.close();
return;
} else {
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] == this) {
threads[j].id = i;
online[i] = true;
}
if (threads[j] != null) {
threads[j].os.println("<Server Message>: A new user " + name + " has logged in");
}
}
}
} else {
os.println("Invalid Username & Password. Terminating");
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
is.close();
os.close();
clientSocket.close();
return;
}
}
}
while (true) {
String line = is.readLine();
System.out.println("#### " + line);
if (line.startsWith("logout")) {
os.println("Successfully logged out");
online[id] = false;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] != null) {
if (threads[i] == this)
threads[i] = null;
else
threads[i].os.println("<Server message>: " + name + " has logged out");
}
}
is.close();
os.close();
clientSocket.close();
return;
}
if (line.startsWith("sendfile ")) {
String subline = line.substring(15);
String temp = line.substring(9, 14);
for (i = 0; i < totalUser; i++) {
if (username[i].equals(temp)) {
break;
}
}
if (i == totalUser) {
os.println("Invalid username");
continue;
}
int k = i;
if (!online[k]) {
os.println("<Failure>: " + temp + " is not online");
} else {
os.println("file sent");
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] != null && threads[j].id == k) {
threads[j].os.println("<" + name + "> " + subline);
}
}
sendFile(subline);
break;
}
}
if (line.startsWith("send ")) {
String subline = line.substring(11);
String temp = line.substring(5, 10);
for (i = 0; i < totalUser; i++) {
if (username[i].equals(temp)) {
break;
}
}
if (i == totalUser) {
os.println("Invalid username");
continue;
}
int k = i;
if (!online[k]) {
os.println("<Failure>: " + temp + " is not online");
}
else {
os.println("message sent");
for (j = 0; j < maxClientsCount; j++) {
if (threads[j] != null && threads[j].id == k) {
threads[j].os.println("<" + name + ">: " + subline);
}
}
}
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = null;
try {
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
clientData = dataInputStream;
} catch (IOException e) {
System.err.println(e);
}
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File " + fileName + " received from client.");
} catch (IOException e) {
System.err.println(e);
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
File file = new File(fileName);
byte[] bytearray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytearray, 0, bytearray.length);
OutputStream os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(bytearray.length);
dos.write(bytearray, 0, bytearray.length);
dos.flush();
System.out.println("File " + fileName + " sent to client.");
} catch (IOException e) {
System.err.println("File does not exist!");
System.err.println(e);
}
}
}
Client side:
package DFT;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientSide implements Runnable {
private static Socket clientSocket = null;
private static PrintStream os = null;
// private static PrintWriter os;
// private static DataInputStream is = null;
private static BufferedReader inputLine, is;
private static boolean closed = false;
private static String username, password;
public static void main(String[] args) {
try {
clientSocket = new Socket("localhost", 2222);
inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new PrintStream(clientSocket.getOutputStream());
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (UnknownHostException unknownHostException) {
System.err.println("Don't know about host");
System.err.print(unknownHostException);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to the host");
System.err.println(e);
}
if (clientSocket != null && os != null && is != null) {
try {
// Creates a thread to read from the server.
new Thread(new ClientSide()).start();
System.out.println("Enter UserName:");
username = inputLine.readLine().trim();
System.out.println("Enter Password:");
password = inputLine.readLine().trim();
os.println("login");
os.println(username);
os.println(password);
while (!closed) {
os.println(inputLine.readLine().trim());
}
os.close();
is.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
#Override
public void run() {
String responseLine;
try {
while ((responseLine = is.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.indexOf("*** Bye") != -1) {
break;
}
}
closed = true;
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = null;
try {
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
clientData = dataInputStream;
} catch (IOException e) {
System.err.println(e);
}
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_client_" + fileName));
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0 && (bytesRead = clientData.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
output.close();
clientData.close();
System.out.println("File " + fileName + " received from client.");
} catch (IOException e) {
System.err.println(e);
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
File file = new File(fileName);
byte[] bytearray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(bytearray, 0, bytearray.length);
OutputStream os = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(file.getName());
dos.writeLong(bytearray.length);
dos.write(bytearray, 0, bytearray.length);
dos.flush();
System.out.println("File " + fileName + " sent to client.");
} catch (IOException e) {
System.err.println("File does not exist!");
System.err.println(e);
}
}
}
It looks like your receiveFile() method is creating the file, but it is never called in your code.