Java simple client server program

2019-03-04 04:47发布

问题:

I have written a simple java code to send a message from server to client and the client should display it respectively. The codes are.

Client.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
   public class Client {

    public static void main(String[] args) throws Exception {
        Socket client_socket = new Socket("localhost", 1235);
        BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
        String serverMsg = null;
        while ((serverMsg = reader.readLine()) != null) {
            System.out.println("Client: " + serverMsg);

        }
    }
}

Server.java

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

public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocket server_socket;
        server_socket = new ServerSocket(1235);
        while (true) {
            Socket mysocket = server_socket.accept();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
            BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
            writer.write("Hello omkar ");

            System.out.println("data sent");
        }
    }

}

Issue: Now the problem is when i run these codes i get the message data sent on server side,but the client console is blank.Please help me find the mistake.

回答1:

In Server code rather than using BufferedWriter, use PrintWriter.

while (true) {
        Socket mysocket = server_socket.accept();

        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);            
        BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
        out.println("Hello World!");

        System.out.println("data sent");
    }

This is working on my system. Try this.



回答2:

You're reading lines but you aren't writing lines. Add a line terminator to the message, or use newline().



回答3:

Referring all your answers and searching a bit on google i have finally got the code running by making the following changes in Server Class.

while (true) {
        Socket mysocket = server_socket.accept();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
        writer.write("Hello omkar \n");
        writer.flush();
        System.out.println("data sent");
    }