简体   繁体   中英

TCP can't receive text messages after sending a file from server in Java

I'm new to socket programming and I have a problem that I can not understand. I am trying to send a file from server to client. After that, server and client start chatting until client says "Bye.". When I start the program, it works well until client sends the "Bye." message and closes its socket. It gives "Couldn't get I/O for the connection to: localhost" exception.

When I try to debug to see what's going on, it holds at while(at line 38) statement even if file transfer finishes. The file delivers correct.

Server Code:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerTCP extends Thread
{ 
    protected Socket clientSocket;

public static void main(String[] args) throws IOException 
{ 
    ServerSocket serverSocket = null; 

    try { 
        serverSocket = new ServerSocket(10008); 
        System.out.println ("Connection Socket Created");
        try { 
            while (true)
            {
                System.out.println ("Waiting for Connection");
                new ServerTCP (serverSocket.accept()); 
            }
        } 
        catch (IOException e) 
        { 
            System.err.println("Accept failed."); 
            System.exit(1); 
        } 
    } 
    catch (IOException e) 
    { 
        System.err.println("Could not listen on port: 10008."); 
        System.exit(1); 
    } 
    finally
    {
        try {
            serverSocket.close(); 
        }
        catch (IOException e)
        { 
            System.err.println("Could not close port: 10008."); 
            System.exit(1); 
        } 
    }
}

private ServerTCP (Socket clientSoc)
{
    clientSocket = clientSoc;
    start();
}

public void run()
{
    System.out.println ("New Communication Thread Started");
    // İlave kısım
    DataInputStream dataIn = null;
    DataOutputStream dataOut = null;

    try {
        //echoSocket = new Socket(serverHostname, 10008);
        dataIn = new DataInputStream(clientSocket.getInputStream());
        dataOut = new DataOutputStream(clientSocket.getOutputStream());

        File file = new File("tmp.txt");
        byte[] contents = new byte[1024];

        FileInputStream fis = new FileInputStream(file);

        int count = 0;
        while( (count =  fis.read(contents)) > 0 ){
            dataOut.write(contents, 0, count);
            dataOut.flush();
        }
        contents[0] = 0;
        count = 1;
        dataOut.write(contents, 0, count);
        dataOut.flush();

        Scanner sc = new Scanner(System.in);
        String clientMessage = null;
        while( !(clientMessage = dataIn.readUTF()).equals("Bye.") )
        {
            System.out.println(clientMessage);
            dataOut.writeUTF(sc.nextLine());
        }

        sc.close();
        fis.close();
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for "
                + "the connection to: ");
        System.exit(1);
    } finally {
        try {
            if (dataOut != null)
                dataOut.close();
            if(dataIn != null)
                dataIn.close();
            clientSocket.close(); 
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }



} 
}

Client Code:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

 public class Client {
public static void main(String[] args) throws IOException {

    String serverHostname = new String ("localhost");

    if (args.length > 0)
        serverHostname = args[0];
    System.out.println ("Attemping to connect to host " +
            serverHostname + " on port 10008.");

    Socket echoSocket = null;
    DataInputStream in = null;
    DataOutputStream dataOut= null;

    try {
        echoSocket = new Socket(serverHostname, 10008);
        in = new DataInputStream(echoSocket.getInputStream());
        dataOut = new DataOutputStream(echoSocket.getOutputStream());

        String clientMessage = "tmp";
        File file = new File(clientMessage + "_got" + ".txt");
        System.out.println(clientMessage + "_got" + ".txt created.");

        FileOutputStream foStream = new FileOutputStream(file);

        byte[] buff = new byte[1024];

        int count = 0;
        while ((count = in.read(buff)) > 0) {
            if(buff[0] == 0)
                break;
            foStream.write(buff, 0, count);
            foStream.flush();
        }

        Scanner keyboard = new Scanner(System.in);
        String msg = "";
        while(true){
            msg = keyboard.next();
            System.out.println("Client: " + msg);
            dataOut.writeUTF(msg);
            System.out.println("Server: " + in.readUTF());
            if( msg.equalsIgnoreCase("Bye.") )
                break;
        }

        System.out.println("asds");
    } 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);
    } finally {
        try {
            if (dataOut != null)dataOut.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    in.close();
    echoSocket.close();
}

}

Edit

My exception is:

java.io.EOFException
    at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
    at java.io.DataInputStream.readUTF(DataInputStream.java:572)
    at java.io.DataInputStream.readUTF(DataInputStream.java:547)
    at Client.main(Client.java:51)
Couldn't get I/O for the connection to: localhost

You've read the input until end of stream in your 'while ' loop, then you're trying to read more input with readUTF(). There isn't any more. Something wrong with your application protocol here. You need to send the file length ahead of the file, and only read that many bytes when reading the sent file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM