読者です 読者をやめる 読者になる 読者になる

シンプルなTCPサーバのサンプル〜その1〜


シンプルなTCPサーバのサンプルです。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class TcpServer {
    private static final int DEFOULT_PORT = 1000;
    private ServerSocket server;

    public TcpServer() throws IOException {
        this(DEFOULT_PORT);
    }
    public TcpServer(int port) throws IOException {
        this.server = new ServerSocket(port);
    }

    public void start() {
        new Thread() {
            @Override public void run() {
                while(true) {
                    try {
                        Socket socket = server.accept(); // block 
                        new Thread(new ConnectionHandler(socket)).start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    class ConnectionHandler implements Runnable {
        private final Socket socket;
        public ConnectionHandler(final Socket socket) {
            this.socket = socket;
        }
        
        @Override public void run() {
            System.out.println("accepted " + socket.getInetAddress() 
                + ":" + socket.getPort());
            try {
                socket.setTcpNoDelay(true);
            } catch (SocketException e) {
                // do nothing
            }
            try {
                handleConversation();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        
        void handleConversation() {
            try {
                InputStream in 
                    = new BufferedInputStream(socket.getInputStream());
                OutputStream out
                    = new BufferedOutputStream(socket.getOutputStream());
                byte[] buffer = new byte[8192];
                int count;
                while((count = in.read(buffer)) >= 0) {
                    System.out.println("received " + count
                            + " bytes from " + socket.getInetAddress()
                            + ":" + socket.getPort());
                    System.out.println(new String(buffer).trim());
                    out.write(buffer, 0, count);
                    out.flush();
                }
                socket.shutdownOutput(); // half close
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        TcpServer tcpServer = new TcpServer();
        tcpServer.start();
    }
}


telnetなどで接続するとエコーします。

telnet localhost 1000

やっつけです・・