PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   26-07-2021

Server

p475 To make a Socket connection, you need to know the IP and the port. Start the server and wait for clients requests.
 
package messages;
import java.io.*;
import java.net.*;

public class TestServer{
    public static void main(String[] args) {
        try {

            ServerSocket serverSocket = new ServerSocket(4242);
            System.out.println("Server started ...");
            
            while(true) {
  
                Socket socket = serverSocket.accept();

                PrintWriter writer = 
                    new PrintWriter(socket.getOutputStream());

                writer.println("Hello Client!"); // write message to client
                writer.close();
            }

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

Client

p478 Make a connection and read from server.
 
package messages;
import java.io.*;
import java.net.*;

public class TestingApp{
    
    public static void main(String[] args) {
    
    System.out.println("Client started");
    
        try {
                // make a connection to the server
            Socket socket = new Socket("127.0.0.1", 4242);
            
                // ask the socket for an input stream
            InputStreamReader streamReader = 
                new InputStreamReader(socket.getInputStream());
            
                // read
            BufferedReader reader = 
                new BufferedReader(streamReader);

            String message = reader.readLine();

            System.out.println("The server message is: " + message);
            
            reader.close();
            
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
    
}
... 17 lines
 

Questions    
Watching Files

        A B C D E F
🔔
1/2