import java.net.*; import java.io.*; public class Client { public static void main(String[] args) throws IOException { Socket socket = new Socket("localhost", 5000); // get the output stream of the socket OutputStream outputStream = socket.getOutputStream(); // write some data to the output stream outputStream.write("Hello, server".getBytes()); // shutdown the output stream socket.shutdownOutput(); // try to write more data to the output stream - will throw IOException outputStream.write("This won't work".getBytes()); // close the socket socket.close(); } }
import java.net.*; import java.io.*; public class Server { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(5000); while (true) { Socket socket = serverSocket.accept(); // read the request from the input stream InputStream inputStream = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String request = reader.readLine(); // send a response OutputStream outputStream = socket.getOutputStream(); outputStream.write("Hello, client".getBytes()); // shutdown the output stream socket.shutdownOutput(); // close the socket socket.close(); } } }Both examples use the java.net package.