Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... Close window without confirm (I.E only) window.opener=null; window.open('','_self'); window.close(); focus on validating function focusOnInvalidControl() {     for (var i = 0; i < Page_Validators.length; i++) {         if (!Page_Validators[i].isvalid) {     ...
Stats
Socket sample
SocketCallBack.java
package bruce.chat;

import java.net.Socket;

public interface SocketCallBack {
    void onAccepted(Socket socket);
}
ChatServer.java
package bruce.chat;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

public class ChatServer {

    private ServerSocket serverSocket;
    private boolean stopFlag;
    private SocketCallBack callback;

    public static ChatServer createEntry(int port) throws IOException {
        ChatServer entry = new ChatServer();
        entry.serverSocket = ServerSocketFactory.getDefault().createServerSocket(port);
        entry.stopFlag = true;

        return entry;
    }

    public static ChatServer createEntry(int port, int backlog, InetAddress ifAddress) throws IOException {
        ChatServer entry = new ChatServer();
        entry.serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, backlog, ifAddress);
        entry.stopFlag = true;

        return entry;
    }

    /**
     * 起始監聽通道
     */
    public void startListen() {
        new Thread() {
            @Override
            public void run() {
                while (ChatServer.this.stopFlag) {
                    try {
                        ChatServer.this.startAccept(ChatServer.this.serverSocket.accept());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        if (ChatServer.this.stopFlag)
                            e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    /**
     * 開始接收資料
     * 
     * @param socket
     *            要接收資料的通訊埠
     */
    private void startAccept(final Socket socket) {
        new Thread() {
            @Override
            public void run() {
                ChatServer.this.callback.onAccepted(socket);

                if (!socket.isClosed()) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void stopListen() {
        this.stopFlag = false;
        try {
            this.serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void setCallback(SocketCallBack callback) {
        this.callback = callback;
    }
}
ChatClient.java
package bruce.chat;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.SocketFactory;

public class ChatClient {

    private Socket socket;

    public void connect(String host, int port) throws UnknownHostException, IOException {
        this.socket = SocketFactory.getDefault().createSocket(host, port);
    }

    public void connect(InetAddress host, int port) throws IOException {
        this.socket = SocketFactory.getDefault().createSocket(host, port);
    }

    public void send(byte[] data) throws IOException {
        this.socket.getOutputStream().write(data);
    }

    public void close() {
        if (this.socket != null)
            try {
                this.socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}
Program.java
package bruce.chat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.Scanner;

public class Program {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        ChatServer server = ChatServer.createEntry(9999);
        server.startListen();
        server.setCallback(new SocketCallBack() {

            @Override
            public void onAccepted(Socket socket) {
                // TODO Auto-generated method stub
                try {
                    InputStream is = socket.getInputStream();

                    System.out.printf("Received at %s :%n", new Date());

                    // ByteBuffer temp = ByteBuffer.allocate(10240);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int readed = -1;
                    byte[] buffer = new byte[512];

                    while ((readed = is.read(buffer)) > 0) {
                        // temp.put(buffer, 0, readed);
                        baos.write(buffer, 0, readed);
                    }
                    

                    // System.out.println(new String(temp.array()));
                    baos.close();
                    System.out.println(baos.toString());

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

        Scanner sc = new Scanner(System.in);
        String line = null;
        while ((line = sc.nextLine()) != null) {
            if ("bye".equalsIgnoreCase(line))
                break;

            ChatClient client = new ChatClient();
            client.connect(InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }), 9999);
            client.send(line.getBytes());
            client.close();

        }

        server.stopListen();
    }

}