2

When I send a String from my client to my server, the server always throws a

java.net.SocketException: Connection reset

If I send a Integer or other types other than a String, the exception would not have been thrown and the program runs absolutely fine.

Client Class:

import java.io.*;
import java.net.*;

public class TestingClient {

    public static void main(String[] args) {
        try {
            Socket clientSocket = new Socket("localhost", 9998);

            DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());

            outputStream.flush();

            outputStream.writeBytes("hello");

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

Server Class:

import java.io.*;
import java.io.IOException;
import java.net.*;

public class TestingServer {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(9998);
            Socket connectionToClient = serverSocket.accept();
            BufferedReader input = new BufferedReader(new InputStreamReader(connectionToClient.getInputStream()));              

            System.out.println(input.readLine());

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}

1 Answer 1

1

Well, "hello" isn't a byte[]. On the client, write the String with DataOutputStream.writeUTF(String) and then flush(). Something like

outputStream.writeUTF("hello");
outputStream.flush();

and on the server, you can't use a BufferedReader. You need something like DataInputStream.readUTF()

DataInputStream dis = new DataInputStream(
        connectionToClient.getInputStream());
System.out.println(dis.readUTF());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.