java socket server examples tcp ip

www.igi‮c.aeditf‬om

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

  1. Create a server socket and bind it to a port:
int port = 8080;

ServerSocket serverSocket = new ServerSocket(port);
  1. Accept a connection from a client:
Socket clientSocket = serverSocket.accept();
  1. Send data to the client:
OutputStream output = clientSocket.getOutputStream();

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

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

System.out.println("Client request: " + request);
  1. Close the client socket:
clientSocket.close();
  1. Close the server socket:
serverSocket.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.