简体   繁体   中英

send objects from server to client in java sockets

I want to send objects from the server to the client in java sockets. I can send them from client to the server, however I am struggling to send them from server to client. I am new to Java so I'm still learning the basics. I know its something relatively minor that I need to do, however i am struggling with it at the moment. Can someone add the bits of code that i am missing?

Open another connection in another thread and let the client be server, and server be client. So in one thread you send A -> B, in another thread you open another socket and begin to send b B -> A.

The problem with low level sockets is that if one side is writing, the other should be listening. That means you have to implement command-query protocol, which is a heavy task. So with my proposal you will use two ports but you know that you will have 2 pipes of data flow.

A --8888--> B
A <--8889-- B

It will be easier if you are just starting with sockets.

You can use ObjectOutputStream to send an object through the socket and ObjectInputStream to receive one:

private ObjectOutputStream oos; 
private ObjectInputStream ois;

public SocketHandler(Socket cs) {
    this.oos = new ObjectOutputStream(cs.getOutputStream());
    this.ois = new ObjectInputStream(cs.getInputStream());
}

public void sendObject(Object o) {
    this.oos.writeObject(o);
    this.oos.flush();
}

public Object receiveObject() {
    return this.ois.readObject();
}

That was assuming you want to send and receive an Object. You can also use PrintWriter and BufferedReader to send and receive String messages and after parsing it:

private PrintWriter pw;
private BufferedReader br;

public SocketHandler(Socket cs) {
    this.pw = new PrintWriter(cs.getOutputStream());
    this.br = new BufferedReader(new InputStreamReader(cs.getInputStream()));
}

public void sendMsg(String msg) {
    this.pw.println(msg);
    this.pw.flush();
}

public String receiveMsg() {
    return this.br.readLine();
}

Below I have an example of some Server-Side code that I used for an application a while ago, then I will give you an explanation as to what's going on here:

first you need to create your ServerSocket in order to accept client requests (as you already know):

ServerSocket serverSocket = new ServerSocket(1002);
        while(true) {

Then you need to enter a while loop in order to receive requests for as long as the Server program is alive

Socket clientSocket = serverSocket.accept();
System.out.println("Connection made to: " + clientSocket);
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String messageString = "";
String line;
System.out.println("Enter while loop to retrieve client message...");
while((line = br.readLine()) != null) {
        String clientRequestLine = line;
        if(clientRequestLine.contains("check return user credentials")) {
        String userNamePassWord = clientRequestLine.replace("check return user credentials", "");
        userNamePassWord = userNamePassWord.trim();
        String[] userNamePassWordSplitter = userNamePassWord.split(" ");
        String userName = userNamePassWordSplitter[0];
        String passWord = userNamePassWordSplitter[1];
        System.out.println("Username: " + userName + "\nPassword: " + passWord);
            boolean isValidUserNamePassWord = ReturnPatientCredentials.checkUserNamePassWord(userName, passWord);
        if(isValidUserNamePassWord) {
                System.out.println("valid");
                out.println("valid");
                    }
        else {
                System.out.println("invalid");
                out.println("invalid");
                    }
                }

Above you need to start a BufferedReader in order to store an InputStream (the data) from the client socket. You also need to create a PrintWriter so that you can send data to the OutputStream and you need to pass your clientSocket as the argument for the OutputStream. Next you'll create variables to get the message and the "line" of date from the client and enter a while loop. You can then store the line in a variable and read the data or whatever you need to do. We use our PrintWriter (out) to send data back with the println() method and then we can break out of the loop when needed.

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