java socket client examples tcp ip

https:‮.www//‬theitroad.com

Here are some examples of how to create a TCP/IP socket client in Java:

  1. Create a socket and connect to a server:
String host = "localhost";
int port = 8080;

Socket socket = new Socket(host, port);
  1. Send data to the server:
OutputStream output = socket.getOutputStream();

String message = "Hello, server!";
output.write(message.getBytes());
  1. Receive data from the server:
InputStream input = socket.getInputStream();
byte[] buffer = new byte[1024];

int length = input.read(buffer);
String response = new String(buffer, 0, length);

System.out.println("Server response: " + response);
  1. Close the socket:
socket.close();

Note that these examples use blocking I/O, which means that the code will pause until data is available to be read from the input stream, or until data has been successfully written to the output stream. If you need to handle multiple connections concurrently, you may want to use non-blocking I/O or a separate thread for each socket.