简体   繁体   中英

Client-Server communication in Java using Sockets

I am trying to write a simple and basic Java program where a client sends the server a string and the server is supposed to respond with a reversed string. I am sure I have the correct program structure and flow but my server is not read the string from my client. I have narrowed the problem to this line on the server side: string = inputStream.readLine(); Here is my code. What could be the problem?

Server1.java

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

class Server1 {

    public static void main(String[] args) throws Exception {
        String string = null;

        ServerSocket myServerSocket = new ServerSocket(4000); //Create Socket
        System.out.println("Server Running...");

        Socket clientSocket = myServerSocket.accept();

        DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
        PrintStream outputStream = new PrintStream(clientSocket.getOutputStream());


        do {
            string = inputStream.readLine();


            if(string!=null){           

            //using StringBuilder method to reverse string
            StringBuilder input = new StringBuilder();

            // append a string into StringBuilder input1
            input.append(input);

            // reverse StringBuilder input1
            input = input.reverse();

            // print reversed String
            for (int i = 0; i < input.length(); i++) {
                outputStream.println(input.charAt(i));
            }
            }

        } while (true);

        /*outputStream.println("exit");
        outputStream.close();
        inputStream.close();
        myServerSocket.close();
        System.out.println("Server Closed!");*/
    }
}

Client1.java

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

import java.util.Scanner;

class Client1 {

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in); //Object to read keyboard input
        String string = null, response = null; //Variable to store string

        Socket mySocket = new Socket("127.0.0.1", 4000); //Create Socket

        DataOutputStream outputStream = new DataOutputStream(mySocket.getOutputStream());
        DataInputStream inputStream = new DataInputStream(mySocket.getInputStream());

        System.out.println("Client Running...");

        do {
            System.out.println("Type in a string and Press Enter...");
            string = sc.next();
            outputStream.writeBytes(string);
            response = inputStream.readLine();
            if (response != null) {
                System.out.println("Server Response: " + response);
            }

        } while (true);

    }
}

The problem is that in this line string = inputStream.readLine(); it is searching for a line and if you wont add "\\r\\n" at the end of your massage it will keep searching for the lines end

I am trying to write a simple and basic Java program where a client sends the server a string and the server is supposed to respond with a reversed string. I am sure I have the correct program structure and flow but my server is not read the string from my client. I have narrowed the problem to this line on the server side: string = inputStream.readLine(); Here is my code. What could be the problem?

Here, I can see copy paste mistake.

// append a string into StringBuilder input1
            input.append(input);

Always use while(true) loop for reading message from the client, Try below codes as for your question.

Server1.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

   public class Server1 {

            private static Socket socket;

            public static void main(String[] args) {
                try {
                    ServerSocket serverSocket = new ServerSocket(4000);
                    System.out.println("Server Running...");

                    //Note: Server is running always. This is done using this while(true) loop
                    while (true) {
                        //Reading the message from the client
                        socket = serverSocket.accept();
                        InputStream is = socket.getInputStream();
                        InputStreamReader isr = new InputStreamReader(is);
                        BufferedReader br = new BufferedReader(isr);
                        String string = br.readLine();
                        System.out.println("Message received from client is " + string);
                        //Reverse string responce builder
                        try {
                            //using StringBuilder method to reverse string
                            StringBuilder input = new StringBuilder();
                            // append a string into StringBuilder input
                            input.append(string);
                            // reverse StringBuilder input
                            input = input.reverse();
                            string = input + "\n"; //Next to line
                            // print reversed String
                            for (int i = 0; i < input.length(); i++) {
                                System.out.println(input.charAt(i));
                            }
                        } catch (Exception e) {
                            //Invalid text message back to client.
                            string = "Please send a proper text message\n";
                        }
                        //Sending the response back to the client.
                        OutputStream os = socket.getOutputStream();
                        OutputStreamWriter osw = new OutputStreamWriter(os);
                        BufferedWriter bw = new BufferedWriter(osw);
                        bw.write(string);
                        System.out.println("Message sent to the client is " + string);
                        bw.flush();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        socket.close();
                    } catch (Exception e) {
                    }
                }
            }
        }

Client1.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client1 {

    private static Socket socket;

    public static void main(String args[]) {
        try {
            socket = new Socket("127.0.0.1", 4000);
            System.out.println("Client Running...");

            //Send the message to the server
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            System.out.println("Type in a string and Press Enter...");
            Scanner sc = new Scanner(System.in);
            String string = sc.next();
            System.out.println("string = " + string);
            String sendMessage = string + "\n"; ////Next to line
            bw.write(sendMessage);
            bw.flush();
            System.out.println("Message sent to the server : " + sendMessage);

            //Get the return message from the server
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String message = br.readLine();
            System.out.println("Message received from the server : " + message);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            //finally close the socket
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

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