0

I'm working on producing a basic two-way socket connection between a client and server in Java. Following some guides I found elsewhere online, I have it working one way, with the server receiving messages from the client, but I was curious on how I would go about making it so the client and server can send messages to each other. I'm also working on implementing a payload, but I'm not worrying about that until after I manage to get the two-way connection working.

This is my code for the server:

import java.net.*;
import java.io.*;
public class ServerDemo {
    private Socket mySocket = null;
    private ServerSocket server = null;
    private DataInputStream input = null;
    
    public ServerDemo(int port)
    {
         try
         {
               server = new ServerSocket(port);
               System.out.println("Server started");
               System.out.println("Waiting for a client ...");
               mySocket = server.accept();
               System.out.println("Client accepted");
               input = new DataInputStream(
                        new BufferedInputStream(mySocket.getInputStream()));
               String newLine = "";
               while (!newLine.equals("Over"))
               {
                    try
                    {
                        newLine = input.readUTF();
                        System.out.println(newLine);
                    }
                    catch(IOException i)
                    {
                        System.out.println(i);
                    }
               }
               System.out.println("Closing connection");
               mySocket.close();
               input.close();
         }
         catch(IOException i)
         {
              System.out.println(i);
         }
    }
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ServerDemo server = new ServerDemo(5000);
    }

}

This is the code for the client:

import java.net.*;
import java.util.Scanner;
import java.io.*;
public class ClientDemo {
    private Socket mySocket = null;
    private BufferedReader input= null;
    private DataOutputStream output = null;

    public ClientDemo(String address, int port)
    {
        try
        {
            mySocket = new Socket(address, port);
            System.out.println("Connected");
            input = new BufferedReader(new InputStreamReader(System.in));
            output = new DataOutputStream(mySocket.getOutputStream());
        }
        catch(UnknownHostException u)
        {
            System.out.println(u);
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
        String newLine = "";
        while (!newLine.equals("Over"))
        {
            try
            {
                newLine = input.readLine();
                output.writeUTF(newLine);
            }
            catch(IOException i)
            {
                System.out.println(i);
            }
        }
        try
        {
            input.close();
            output.close();
            mySocket.close();
        }
        catch(IOException i)
        {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        String response="";
        Scanner myScanner = new Scanner(System.in);
        System.out.println("Please enter a server to connect to.");
        response=myScanner.next();
        ClientDemo client = new ClientDemo(response, 5000);
    }
}

I would appreciate any advice on how to convert this into two-way communication.

1 Answer 1

1

In order for the server to send a message back to the client, you have to respond from the server (ServerDemo) to the client using mySocket.getOutputStream()

There are multiple ways of doing it,

Using OutputStreamWriter

BufferedWriter buffer = new BufferedWriter(new OutputStreamWriter(mySocket.getOutputStream(), "UTF8"));
buffer.append(stringToSend).append("\n");
buffer.append("Over").append("\n");
buffer.flush();

Using PrintWriter

PrintWriter out = new PrintWriter(mySocket.getOutputStream());
String response = "Data received successfully";
out.print(response);

To print the response from the server following code snippet can be used in the ClientDemo try/catch block where the socket is closed.

BufferedReader bufferIn=new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
String message;
while(!(message = bufferIn.readLine()).equals("Over")){
    System.out.println(message);
}
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.