Socket connection and concurrent package : Socket « Network Protocol « Java

Socket connection and concurrent package


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorHttpd {
  ExecutorService executor = Executors.newFixedThreadPool(3);

  public void start(int port) throws IOException {
    final ServerSocket ss = new ServerSocket(port);
    while (!executor.isShutdown())
      executor.submit(new TinyHttpdConnection(ss.accept()));

  public void shutdown() throws InterruptedException {
    executor.awaitTermination(30, TimeUnit.SECONDS);

  public static void main(String argv[]) throws Exception {
    new ExecutorHttpd().start(Integer.parseInt(argv[0]));

class TinyHttpdConnection implements Runnable {
  Socket client;

  TinyHttpdConnection(Socket client) throws SocketException {
    this.client = client;

  public void run() {
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(),
      OutputStream out = client.getOutputStream();
      PrintWriter pout = new PrintWriter(new OutputStreamWriter(out, "8859_1"), true);
      String request = in.readLine();
      System.out.println("Request: " + request);

      byte[] data = "hello".getBytes();
      out.write(data, 0, data.length);
    } catch (IOException e) {
      System.out.println("I/O error " + e);


Related examples in the same category

1.Create a socket without a timeout
2.Create a socket with a timeout
3.Demonstrate Sockets.
4.XML based message
5.ObjectInputStream and ObjectOutputStream from Socket
6.ServerSocket and Socket for Serializable object
7.String based communication between Socket
8.Get email with Socket
9.Create PrintWriter from BufferedWriter, OutputStreamWriter and Socket
10.Read from server
11.Use Socket to read and write stream
12.Connects to a server at a specified host and port. It reads text from the console and sends it to the server
13.A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection
14.Reading Text from a Socket
15.Writing Text to a Socket
16.Sending a POST Request Using a Socket
17.Get the Date from server
18.Transfer a file via Socket
19.Ping a server
20.Read and write through socket
21.Read float number from a Socket
22.Read Object from Socket
23.deleting messages from a POP3 mailbox based on message size and Subject line
24.A timeout feature on socket connections
25.Write Objects From Socket
26.Write Double Using Sockets
27.Download WWW Page
28.Redirects incoming TCP connections to other hosts/ports
29.Socket Fetcher
30.Socket Address Encoder
31.Zip socket
32.This program shows how to interrupt a socket channel.
33.This program shows how to use sockets to send plain text mail messages.
34.Makes a socket connection to the atomic clock in Boulder, Colorado, and prints the time that the server sends.