Males Koding

Icon

Blog yang isinya ternyata banyak kodingannya

Java Socket Programming: Simultaneous Connections

Salah satu cara mengatasi kemungkinan timeout yang diakibatkan oleh blocking pada postingan sebelumnya adalah dengan menggunakan multithread.

Proses streaming ditangani oleh sebuah Thread yakni

package simpleserver;

import java.io.*;
import java.net.*;
import java.util.*;

public class SocketThread implements Runnable {

    private Socket socket;

    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    public void run() {

        //Membuat stream input/output dari client socket
        PrintWriter out;
        try {
            out = new PrintWriter(this.socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

            Thread.sleep(3000);

            //Menampilkan string yang dikirim oleh client
            System.out.println(in.readLine());
            //Mengirimkan string "Hello!" ke client
            out.println("Hello World, Client!");

            //Menutup koneksi dan stream
            out.close();
            in.close();
            this.socket.close();
        } catch (IOException ex) {

        } catch (InterruptedException ex){

        }

    }
}

Di servernya tinggal

public static void main(String[] args) throws IOException, InterruptedException {
        //Membuat Server Socket
        ServerSocket serverSocket = null;
        try {
            //Mencoba untuk binding ke port 4444
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }

        //Membuat client Socket
        Socket clientSocket = null;
        while (true) {
            try {
                //Mencoba menerima koneksi socket dari client
                clientSocket = serverSocket.accept();
                SocketThread s = new SocketThread(clientSocket);
                s.run();
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }

        }
    }

Dengan demikian setelah sebuah socket selesai melakukan blocking untuk mencoba menerima koneksi maka aplikasi akan membangkitkan sebuah thread sehingga thread utama dapat kembali melakukan blocking untuk socket yang baru selagi thread yang dibangkitkan melakukan aktivitas dengan koneksi socket yang baru saja aktif.

Filed under: Dedicated, Java, Lecture, Medium, Network Programming, Snippets, Web Programming, tutorial , , , , ,

One Response

  1. dwi ardi irawan mengatakan:

    pas, aq lg nyari ini. thnx u ….

Leave a Reply

About Me

avatar
Just a man who only knows how to code but really dislike doing it

Contact Me





Top Rated

Twitter Terbaru