//Client code Socket clientSocket = new Socket("localhost", 8080); //Server code ServerSocket serverSocket = new ServerSocket(8080); Socket connectionSocket = serverSocket.accept();
//Client code Socket clientSocket = new Socket("localhost", 8080); OutputStream outToServer = clientSocket.getOutputStream(); String message = "Hello server!"; outToServer.write(message.getBytes()); //Server code ServerSocket serverSocket = new ServerSocket(8080); Socket connectionSocket = serverSocket.accept(); InputStream inFromClient = connectionSocket.getInputStream(); byte[] buffer = new byte[1024]; int bytesRead = inFromClient.read(buffer); String message = new String(buffer, 0, bytesRead); System.out.println("Received message from client: " + message);In this example, the client sends a message to the server by writing to the OutputStream of the Socket object. The message is converted to bytes using the getBytes() method of the String class. On the server side, the InputStream of the Socket object is used to read the incoming data. The read() method returns the number of bytes read, which is then used to construct a String from the buffer. Both examples use the java.net package library, which is part of the core Java API.