tags:

views:

132

answers:

2

Hi,I have Client class and Server class but when i run both main methods and then nothing will happen and when i stop running ,this exception will be occurred. why?? please help me,how can I fix it???

my Client class:

public class Client {

static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    try {
        Socket c = new Socket("localhost", 5001);
        BufferedReader read = new BufferedReader(new InputStreamReader(c.getInputStream()));
        BufferedWriter write = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
        String string = reader.readLine();
        write.write(string, 0, string.length());
        write.newLine();
        write.flush();
        System.out.println(read.readLine());



    } catch (Exception e) {
        System.err.println(e);
    }
}}

my Server class:

public class Server{

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    ServerSocket s = null;
    try {
        s = new ServerSocket(5001);
        System.out.println("listening...");
        Socket so = s.accept();
        BufferedReader read = new BufferedReader(new InputStreamReader(so.getInputStream()));
        BufferedWriter write = new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));
        while (true) {
            String string = read.readLine();
            System.out.println(string);
            String answer = "I got" + string + "from you!";
            write.write(answer, 0, answer.length());
            write.newLine();
            write.flush();
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

}}

stacktrace in server cpnsole:

run:


listening...
system connected
Hello

Dec 19, 2009 12:58:15 PM server.Main main
SEVERE: null
java.net.SocketException: Connection reset
        at java.net.SocketInputStream.read(SocketInputStream.java:168)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
        at java.io.InputStreamReader.read(InputStreamReader.java:167)
        at java.io.BufferedReader.fill(BufferedReader.java:136)
        at java.io.BufferedReader.readLine(BufferedReader.java:299)
        at java.io.BufferedReader.readLine(BufferedReader.java:362)
        at server.Main.main(Main.java:37)
BUILD SUCCESSFUL (total time: 9 seconds)

in Client console:

run:
Hello
I gotHellofrom you!
BUILD SUCCESSFUL (total time: 4 seconds)
+2  A: 

Your client connects to the server, sends some data, reads the response and terminates. That's ok.

But your server waits for a client, reads its data, writes a response and then tries to read some data from the client again. But the client has closed the connection. So the server gets the exception you described.

To fix this (on server side), you have to do the Socket so = s.accept(); within your while loop. And don't forget to close the socket at the end of the loop.

tangens
Thanks,I get it
Johanna
A: 

First. A BufferedWriter isn't useful with Sockets. Use a PrintWriter witch flushes automatically.

PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);// true means "flush automatically"
writer.println(reader.readLine());
// Now you don't have to add a newline and flush.


Edit

Secondly. The reason why the exception is thrown is because the client closes the Socket after writing your input to the Server. The server is still waiting for another String to read. But he can't because the Socket is closed. You don't close it literally. But the program ends there. So Java think: "Nothing left to do, exit". By exiting, the connection closes.

To solve it you have to put the communication in a while(true) loop and, to stop the connection in a correct way, send an "end-of-connection" message.

Client side:

while (true)
{
    String userinput = reader.readLine(); // From System.in
    writer.writeln(userinput);
    if (userinput.equals("end"))
    {
        socket.close();
        break; // break out of the while(true) loop
    }
}

Server side:

while (true) {
    String socketinput = reader.readLine();
    if (socketinput.equals("end"))
    {
        socket.close();
        break; // Break out of the while(true) loop.
    }
    ... // Handle the socketInput
}

That is also what "Connection reset" means.

Martijn.

Martijn Courteaux
Thanks a lot for your recommendation[:-)].
Johanna
but remember that `PrintWriter` methods do not throw IOException, you should use `checkError()` to check for errors
Carlos Heuberger