I am creating a Server Client program which works before I try to implement multithreading on the server. I am unsure what is causing the issue. The client connects to the server, after selecting the upload or download option and sends the first line of the file, then the client crashes with this exception:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at Client.upload(Client.java:66)
at Client.main(Client.java:99)
Client Code
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void download(String filename)
{
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
socket = new Socket(host.getHostName(), 8001);
Writer out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(filename),"utf8"));
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Download");
oos.writeObject(filename);
oos.close();
socket.close();
while(true)
{
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Line request sent");
oos.writeObject("Request");
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
ois.close();
socket.close();
}
out.close();
oos.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void upload(String filename)
{
try {
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
BufferedReader in = new BufferedReader(new FileReader(filename));
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Upload");
oos.writeObject(filename);
oos.close();
socket.close();
String line = null;
while((line = in.readLine()) != null) {
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending line to Socket Server");
oos.writeObject(line);
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
ois.close();
oos.close();
Thread.sleep(100);
}
socket = new Socket(host.getHostName(), 8001);
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending end of file to Server");
oos.writeObject("%end%");
oos.close();
socket.close();
in.close();
}
catch(IOException | ClassNotFoundException | InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
int i = 0;
Scanner scanner = new Scanner(System.in);
do
{
System.out.println("Enter '-u' to upload or '-d' to download");
String input = scanner.next();
System.out.println("Enter the filename");
String filename = scanner.next();
if(input.equalsIgnoreCase("-u")) {
System.out.println("Uploading " + filename);
upload(filename);
i = 0;
}
else if(input.equalsIgnoreCase("-d")) {
System.out.println("Downloading " + filename);
download(filename);
i = 0;
}
else{
System.out.println("Invalid input try again");
i = 1;
}
}while(i == 1);
scanner.close();
}
}
Server Code before multithreading
import java.io.*;
import java.lang.ClassNotFoundException;
import java.net.*;
public class Server
{
private static ServerSocket server;
private static int port = 8001;
public static void upload(String fileName)
{
try {
System.out.println("File Uploading");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),
"utf-8"));
System.out.println("Created " + fileName);
while(true)
{
System.out.println("Waiting for next line");
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
System.out.println("Message Received: " + message);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Server Received: " + message);
ois.close();
oos.close();
socket.close();
}
out.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void download(String fileName)
{
try {
Socket socket = null;
System.out.println("Selected Download");
System.out.println(fileName + " Downloading");
BufferedReader in = new BufferedReader(new FileReader(fileName));
ObjectOutputStream oos = null;
String line = null;
while((line = in.readLine()) != null)
{
try
{
socket = server.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(line);
System.out.println("Line " + line + " sent to client");
oos.close();
Thread.sleep(100);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("Sending end of file");
Socket endSocket = server.accept();
ObjectOutputStream end = new ObjectOutputStream(endSocket.getOutputStream());
end.writeObject("%end%");
end.close();
in.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException, ClassNotFoundException
{
while(true)
{
try {
server = new ServerSocket(port);
System.out.println("Waiting for upload or download request from client");
Socket socketUpDown = server.accept();
ObjectInputStream request = new ObjectInputStream(socketUpDown.getInputStream());
String upDown = (String)request.readObject();
if(upDown.equals("Upload"))
{
upload((String)request.readObject());
}
else if(upDown.equals("Download"))
{
download((String)request.readObject());
}
socketUpDown.close();
}
catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
}
Server Code After Multithreading
import java.io.*;
import java.lang.ClassNotFoundException;
import java.net.*;
public class Server
{
private static ServerSocket server;
private static int port = 8001;
public static void main(String args[]) throws IOException, ClassNotFoundException
{
try
{
server = new ServerSocket(port);
int counter = 0;
System.out.println("Server Started ....");
while(true)
{
counter++;
Socket serverClient = server.accept();
System.out.println("A new client is connected : " + serverClient);
ServerClientThread sct = new ServerClientThread(serverClient, counter);
sct.start();
}
}catch(Exception e){
e.printStackTrace();
}
}
private static class ServerClientThread extends Thread
{
private int clientNo;
public ServerClientThread(Socket socket, int clientNo)
{
this.clientNo = clientNo;
}
public void run()
{
try {
System.out.println("Waiting for upload or download request from client");
Socket socketUpDown = server.accept();
ObjectInputStream request = new ObjectInputStream(socketUpDown.getInputStream());
String upDown = (String)request.readObject();
if(upDown.equals("Upload"))
{
upload((String)request.readObject());
}
else if(upDown.equals("Download"))
{
download((String)request.readObject());
}
socketUpDown.close();
}
catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
finally{
System.out.println("Client -" + clientNo + " exit!! ");
}
}
public static void upload(String fileName)
{
try {
System.out.println("File Uploading");
Writer out = new BufferedWriter(new OutputStreamWriter(new
FileOutputStream(fileName), "utf-8"));
System.out.println("Created " + fileName);
while(true)
{
System.out.println("Waiting for next line");
Socket socket = server.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
if(message.equalsIgnoreCase("%end%"))break;
out.write(message + "\n");
System.out.println("Message Received: " + message);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject("Received" + message);
ois.close();
oos.close();
socket.close();
}
out.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void download(String fileName)
{
try {
Socket socket = null;
System.out.println("Selected Download");
System.out.println(fileName + " Downloading");
BufferedReader in = new BufferedReader(new FileReader(fileName));
ObjectOutputStream oos = null;
String line = null;
while((line = in.readLine()) != null)
{
try{
socket = server.accept();
oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(line);
System.out.println("Line " + line + " written to file");
oos.close();
Thread.sleep(100);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Sending end of file");
Socket endSocket = server.accept();
ObjectOutputStream end = new ObjectOutputStream(endSocket.getOutputStream());
end.writeObject("%end%");
end.close();
in.close();
System.out.println("Shutting down Socket server!!");
server.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
}
}
Related
I need to transfer few files to different computers, 1 file per 1 computer. Now i can only transfer 1 file to 1 computer. Also some computers from my IP pool can be offline, how can i avoid Exception?
Also I have all code in github:
https://github.com/xym4uk/Diplom/tree/master/src/xym4uk/test
Client
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileClient {
private static Socket sock;
private static String fileName;
private static BufferedReader stdin;
private static PrintStream ps;
public static void main(String[] args) throws IOException {
public static void sendFile(File myFile) {
//connecting
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("1");
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File " + myFile.getName() + " sent to Server.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
DataBase.setRecord(sock.getInetAddress().toString(), myFile.getName());
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void receiveFile(String fileName) {
try {
sock = new Socket("localhost", 4444);
ps = new PrintStream(sock.getOutputStream());
ps.println("2");
ps.println(fileName);
} catch (Exception e) {
System.err.println("Cannot connect to the server, try again later.");
System.exit(1);
}
try {
int bytesRead;
InputStream in = sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(("received_from_server_" + 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();
in.close();
System.out.println("File " + fileName + " received from Server.");
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package xym4uk.test;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer {
private static ServerSocket serverSocket;
private static Socket clientSocket = null;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(4444);
System.out.println("Server started.");
} catch (Exception e) {
System.err.println("Port already in use.");
System.exit(1);
}
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Accepted connection : " + clientSocket.getInetAddress());
Thread t = new Thread(new CLIENTConnection(clientSocket));
t.start();
} catch (Exception e) {
System.err.println("Error in connection attempt.");
}
}
}
}
ClientConnection
package xym4uk.test;
import java.io.*;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class CLIENTConnection implements Runnable {
private Socket clientSocket;
private BufferedReader in = null;
public CLIENTConnection(Socket client) {
this.clientSocket = client;
}
#Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String clientSelection;
while ((clientSelection = in.readLine()) != null) {
switch (clientSelection) {
case "1":
receiveFile();
break;
case "2":
String outGoingFileName;
while ((outGoingFileName = in.readLine()) != null) {
sendFile(outGoingFileName);
}
break;
default:
System.out.println("Incorrect command received.");
break;
}
in.close();
break;
}
} catch (IOException ex) {
Logger.getLogger(CLIENTConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void receiveFile() {
try {
int bytesRead;
DataInputStream clientData = new DataInputStream(clientSocket.getInputStream());
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 ex) {
System.err.println("Client error. Connection closed.");
}
}
public void sendFile(String fileName) {
try {
//handle file read
File myFile = new File(fileName);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);
//handle file send over socket
OutputStream os = clientSocket.getOutputStream();
//Sending file name and file size to the client
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("File "+fileName+" sent to client.");
} catch (Exception e) {
System.err.println("File does not exist!");
}
}
}
I am making 2 classes for Chat server client for a project I am working on. The problem is server can see the message that sent to it(from client) and it can send those messages out to every clients BUT each client has to type in some input first if he wants to see the message from other users. I have no clue what I did wrong. Please help me out. Thanks in advance :)
Server Class
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class TestServer extends Thread
{
protected Socket clientSocket;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
final static int PORT = 22;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
System.out.println ("Connection Socket Created");
try
{
while (true)
{
System.out.println ("Waiting for Connection");
Socket sock = serverSocket.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
new TestServer (sock);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private TestServer (Socket inSock)
{
clientSocket = inSock;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
//System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while (true)
{
inputLine = in.readLine();
System.out.println ("Server: " + inputLine);
for(int i = 1; i <= TestServer.ConnectionArray.size(); i++)
{
System.out.println("Total Connection: " + ConnectionArray.size());
Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i-1);
if (clientSocket != TEMP_SOCK)
{
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
TEMP_OUT.println(inputLine);
TEMP_OUT.flush();
System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
}
}
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client Class
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname);
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 22);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("Other user: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need a separate thread in the client for reading from the server without blocking on System.in;
Thread t = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Other user: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
}
t.interrupt();
I'm trying to send a file between server and client but when I'm trying to write into socket I'm getting java.net.SocketException: Connection reset by peer: socket write error.
//server side
package tcp;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.util.*;
public class ServerSock {
static ServerSocket Socket1;
static int port=2500;
public static void main(String[] args) {
Socket server;
File filename=new File("C:/Users/Sudhir/Desktop/mot.wmv");
byte[] serverBuffer=new byte[(int)filename.length()];
StringBuffer msgFromClient= new StringBuffer();
String timeStamp;
try {
Socket1=new ServerSocket(port);
System.out.println("Server Socket is initialised");
int c;
server=Socket1.accept();
BufferedInputStream serverInputBuffer = new BufferedInputStream(server.getInputStream());
InputStreamReader serverInputStream = new InputStreamReader(serverInputBuffer);
while((c=serverInputStream.read())!=13) {
msgFromClient.append((char)c);
}
System.out.println(msgFromClient);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
timeStamp=new Date().toString();
//String filename = "test.pdf";
//byte[] serverBuffer=new byte[1024*33];
String respond = "Server responded at "+ timeStamp + (char) 13;
//System.out.println(respond);
//BufferedOutputStream bos = new BufferedOutputStream(server.getOutputStream());
//OutputStreamWriter osw = new OutputStreamWriter(bos);
FileInputStream fis=new FileInputStream(filename);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(serverBuffer,0,serverBuffer.length);
OutputStream os=server.getOutputStream();
try{
os.write(serverBuffer,0,serverBuffer.length);
}catch(IOException e2){
System.out.println(e2);
}
//String serverMessage=new String(serverBuffer);
//serverMessage+=(char)13;
//osw.write(respond);
os.flush();
server.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
//clientside
package tcp;
import java.io.*;
import java.net.*;
import java.util.*;
public class ClientSocket {
public static void main(String[] args) {
String host="127.0.0.1";
int port=2500;
StringBuffer msgFromServer = new StringBuffer();
String timeStamp;
byte clientBuffer[]=new byte[732419705];
System.out.println("Client Socket is initialised");
try {
InetAddress serverAddress=InetAddress.getByName(host);
try {
Socket clientSocket=new Socket(serverAddress,port);
BufferedOutputStream clientOutputBuffer = new BufferedOutputStream(clientSocket.getOutputStream());
OutputStreamWriter clientOutputStream = new OutputStreamWriter(clientOutputBuffer);
timeStamp=new Date().toString();
String clientMessage="Calling Server on "+host +" port" +port +" at" +timeStamp + (char)13;
clientOutputStream.write(clientMessage);
clientOutputStream.flush();
//BufferedInputStream clientInputBuffer= new BufferedInputStream(clientSocket.getInputStream());
//InputStreamReader clientInputStream = new InputStreamReader(clientInputBuffer);
int c;
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// while((c=clientInputStream.read())!=13){
// msgFromServer.append((char)c);
//}
FileOutputStream fos=new FileOutputStream("C:/Users/Sudhir/Desktop/sud.wmv");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream is = clientSocket.getInputStream();
int readbytes=is.read(clientBuffer,0,clientBuffer.length);
bos.write(clientBuffer,0,readbytes);
//System.out.println(msgFromServer);
//System.out.println("end");
bos.close();
clientSocket.close();
} catch (IOException e) {
System.out.println(e);
}
} catch (UnknownHostException e) {
System.out.println(e);
}
}
}
I wrote some client - server program, that shares data but at server side i got EOFException after reciving data. I tried to fix it on my own but it is hard to find own errors.
The error is caused by this line: Message command =(Message) serInputStream.readObject();
Here is some output from server:
java.io.EOFException
at Java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at transfer.Serwerus.run(Serwerus.java:42)
Server code:
import java.io.*;
import java.net.*;
public class Serwerus implements Runnable
{
public InputStream is;
public FileOutputStream fos;
public BufferedOutputStream bos;
public ObjectOutputStream serOutputStream;
public ObjectInputStream serInputStream;
ServerSocket socket;
private String clientMessage, clientFileName;
private int clientFileSize;
public Serwerus()
{
try
{
socket = new ServerSocket(6060);
System.out.println("Server started....");
}
catch(IOException e)
{
System.err.println("Error: " + e);
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
Socket sock = socket.accept();
System.out.println("Client accepted");
serOutputStream = new ObjectOutputStream(sock.getOutputStream());
serInputStream = new ObjectInputStream(sock.getInputStream());
while (true)
{
Message command =(Message) serInputStream.readObject();
System.out.println("after readObject");
if (command.getCommand().startsWith("FileU"))
{
System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
serOutputStream.writeObject(new Message("Bring", "", 0));
//ReciveData(socket, command.getfileName(), command.getfileSize());
}
else if(command.getCommand().startsWith("Wait"))
{
System.out.println("hohoho");
ReciveData(sock, command.getfileName(), command.getfileSize());
}
else if(command.getCommand().startsWith("Quit"))
{
System.exit(1);
}
else
{
System.out.println("Unknow");
}
}
}
catch(ClassNotFoundException | IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
serInputStream.close();
serOutputStream.close();
socket.close();
}
catch (IOException e)
{
System.err.println("Fallen on closing socket.\n Error: " + e);
}
}
}
public void SendData(Socket sock, String filePath) throws Exception
{
File myFile = new File (filePath);
System.out.println("File name = " + myFile.getName() + " File len = " + (int)myFile.length());
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
System.out.println("Sending finished");
}
public void ReciveData(Socket sock, String filePath, int fileSize)
{
System.out.println("Recive in progress, filesize = " + fileSize);
int bytesRead = 0, current = 0;
byte[] array = new byte[fileSize];
try
{
is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
do
{
System.out.println(bytesRead);
bytesRead = is.read(array);
current += bytesRead;
}
while(bytesRead > -1);
bos.write(array, 0 , current);
bos.flush();
bos.close();
fos.close();
// sock.close();
System.out.println("Reciveing finished");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void main (String [] args ) throws IOException
{
new Thread(new Serwerus()).start();
}
}
Client code:
import java.io.*;
import java.net.*;
public class Clientus implements Runnable
{
InputStream is;
FileOutputStream fos;
BufferedOutputStream bos;
ObjectOutputStream cliOutputStream;
ObjectInputStream cliInputStream;
Socket socket;
File actFile;
private String serverMessage, serverFileName;
private int serverFileSize;
public Clientus()
{
try
{
socket = new Socket("localhost", 6060);
cliOutputStream = new ObjectOutputStream(socket.getOutputStream());
cliInputStream = new ObjectInputStream(socket.getInputStream());
File file = new File(<filepath>);
actFile = file;
}
catch (Exception e)
{
System.err.println("Error: " + e);
e.printStackTrace();
}
}
#Override
public void run()
{
try
{
cliOutputStream.writeObject(new Message("FileU", actFile.getPath(), (int) actFile.length()));
cliOutputStream.flush();
//while (true)
//{
Message command =(Message) cliInputStream.readObject();
if (command.getCommand().startsWith("File"))
{
String name = command.getfileName();
int size = command.getfileSize();
System.out.println("Name = " + command.getfileName() + ", size= " + command.getfileSize());
if(size != 0 && !"".equals(name))
{
//ReciveData(socket, 0);
}
}
else if(command.getCommand().startsWith("Bring"))
{
cliOutputStream.writeObject(new Message("Wait", "D:\\KP2\\Serwer\\dupa.txt",(int) actFile.length()));
cliOutputStream.flush();
try
{
SendData(socket, actFile.getPath());
//this.socket.close();
}
catch (Exception ex)
{
System.err.println("Error with: SendData()");
}
}
else if(command.getCommand().startsWith("Quit"))
{
System.exit(1);
}
else
{
System.out.println("Command unknown");
}
//}
}
catch(ClassNotFoundException | IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
socket.close();
cliOutputStream.close();
cliInputStream.close();
}
catch (IOException e)
{
System.err.println("Fallen on closing socket.\n Error: " + e);
}
}
}
public void SendData(Socket sock, String filePath) throws Exception
{
byte [] mybytearray = new byte [(int) new File(filePath).length()];
FileInputStream fis = new FileInputStream(filePath);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
fis.close();
bis.close();
os.close();
System.out.println("Sending finished");
}
public void ReciveData(Socket sock, String fileName, int fileSize)
{
int bytesRead, current = 0;
byte[] array = new byte[fileSize+1];
try
{
is = sock.getInputStream();
fos = new FileOutputStream(<file_path>);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(array,0,array.length);
current = bytesRead;
do
{
bytesRead = is.read(array, current, (array.length - current));
if(bytesRead >= 0)
current += bytesRead;
}
while(bytesRead > -1);
bos.write(array, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println("Send time: " + (end - start));
bos.close();
sock.close();
System.out.println("Reciveing finished");
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
public static void main (String [] args ) throws IOException
{
new Thread(new Clientus()).start();
}
}
Can anyone help?
Your client may be disconnected after sending data and because your server is waiting for more data, the EOFException will occurr.
To fix this problem, you can add try-catch block to catching this exception when the client disconnects.
You are using both the ObjectOutputStream and the socket's own OutputStream to send data on, and you are getting out of sync. When you send the raw data directly over the socket you aren't sending the length first, so the receiver doesn't know how many bytes belong to this transmission. In fact it just reads everything until EOS, so next time you call ObjectInputStream.readObject() it naturally gets an EOFException. To fix this:
Use the ObjectInputStream and ObjectOutputStream for everything.
Before sending the file, send its length, via writeLong().
At the receiver, when receiving the file, first get its length, via readLong(), then read exactly that many bytes from the ObjectInputStream and copy them to the file.
I have Socket- Client application. The code below is supposed to allow client to both read replies from server and read input at the same time. The thing is- this code "works" while debugging in eclipse, as in I recieve messages outside of normal flow in a process I'm debugging, but If i launch application normally, it completly ignores that proces? What is the most common cause of "IDE working, real life not" syndrome?
Whole files:
Server:
public class Server implements Runnable {
static ServerSocket serverSocket;
Socket tempSocket;
Socket tempSocket2;
static volatile List<User> usersList = new ArrayList<User>();
static boolean waitForNew = true;
PrintWriter tempOut;
volatile User[] tempUser;
volatile boolean isReadingN = false;
public Server(Socket _s, Socket _s2) {
tempSocket = _s;
tempSocket2 = _s2;
}
public Server(PrintWriter nOut, User[] user) {
tempOut = nOut;
tempUser = user;
isReadingN = true;
}
#Override
public void run() {
if (isReadingN) {
while (true) {
if (tempUser != null && tempUser.length > 0
&& tempUser[0] != null)
break;
}
User[] myUser = new User[1];
myUser[0] = tempUser[0];
// myUser[0]=usersList.
while (true) {
if (myUser[0].isCurrentlyLoggedIn() == false)
break;
String[] toSend = null;
if (myUser[0].isNotificable())
toSend = myUser[0].printNotifications().split("\n");
else
continue;
//tempOut.println("");
int sendL=toSend.length;
tempOut.println(String.valueOf(sendL));
for (int i = 0; i < toSend.length; i++)
tempOut.println(toSend[i]);
}
return;
}
Socket clientSocket = tempSocket;
System.out.println("Initiating conversation with the client");
String inputLine;
try {
System.out.print("creating server out...");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true);
Socket iClientSocket = tempSocket2;
ObjectOutputStream iout = new ObjectOutputStream(
iClientSocket.getOutputStream());
System.out.println("OK!");
System.out.print("creating server in...");
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
System.out.println("OK!");
System.out.print("creating server image streams...");
System.out.println("OK!");
System.out.println("Server initiating conversation");
User[] currentUser = new User[1];
new Thread(new Server(out, currentUser)).start();
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
boolean[] downloadPicture = new boolean[1];
downloadPicture[0] = false;
String input = Command.call(inputLine, currentUser, usersList,
downloadPicture);
String[] toSend;
if (input != null) {
toSend = input.split("\n");
} else
toSend = new String[0];
out.println(String.valueOf(toSend.length));
for (int i = 0; i < toSend.length; i++)
out.println(toSend[i]);
if (downloadPicture[0]) {
System.out.println("File sent.");
iin.close();
} else{
out.println("1");
out.println("Error: File does not exit.");}
} else
//out.println(" ");
if (inputLine.equals("EXIT")) {
waitForNew = false;
break;
}
}
// End communication graciously
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IIOException e) {
System.out.println("Error: Could not find file");
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
// Create socket on port given in argument, localhost
if (args.length == 0) {
System.out
.println("Not enough arguments. Try Server <port number>");
System.exit(-1);
}
int port = 0;
try {
port = Integer.valueOf(args[0]);
System.out.println("Application start");
serverSocket = new ServerSocket(port);
System.out.println("Created socket on port " + port);
} catch (NumberFormatException c) {
System.out
.println("Incorrect port number. Try Server <port number>");
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
// Waiting for client
System.out.println("Waiting for client...");
Socket clientSocket = null;
Socket iClientSocket = null;
while (waitForNew) {
try {
clientSocket = serverSocket.accept();
iClientSocket = serverSocket.accept();
new Thread(new Server(clientSocket, iClientSocket)).start();
} catch (IOException e) {
System.out.println("Accept failed: " + port);
System.exit(-1);
}
}
}
}
Client:
public class Client implements Runnable {
static Socket clientSocket = null;
static Socket iClientSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static InputStream iin = null;
public static void main(String[] args) {
int port = Integer.valueOf(args[1]);
String host = args[0];
try {
clientSocket = new Socket(host, port);
iClientSocket = new Socket(host, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
iin = iClientSocket.getInputStream();
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + host);
System.exit(-1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + "the connection to: "
+ host);
System.exit(-1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(
System.in));
String userInput;
try {
new Thread(new Client()).start();
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
}
System.out.println("Closing sockets, closing streams");
out.close();
in.close();
stdIn.close();
iClientSocket.close();
clientSocket.close();
} catch (IOException e) {
System.exit(-1);
}
}
#Override
public void run() {
String a = null;
try {
while (true) {
if((a = in.readLine()) == null)
continue;
int n;
try{
n = Integer.valueOf(a);
}catch(NumberFormatException e){
System.out.println(a);
n=1;
//continue;
}
a = "";
for (int i = 0; i < n; i++)
a += in.readLine() + "\n";
System.out.println(a);
// if(a.contains("POST"),)
if (a.compareToIgnoreCase("EXIT") == 0) {
System.out.println("Exiting");
break;
}
if (a.endsWith("Sending File\n")) {
System.out.println("Recieving image.");
(some unimportant for now code)
System.out.println("Image recieved");
}
}
} catch (IOException e) {
}
}
}