Home > Pemrograman Java > Java: Contoh Server Socket Sederhana

Java: Contoh Server Socket Sederhana


Contoh ini mengenalkan pemrograman soscket dengan Java. Server mendengar (listen) koneksi yang masuk. Ketika suatu koneksi terbangun, client dapat mengirimkan data. Pada kode di bawah ini, client mengirimkan pesan “Hi my server”. Client mengirimkan pesan khusus “bye” untuk menghentikan koneksi dari server. Kemudian server mengirimkan pesan “bye” juga. Terakhir, koneksi diakhiri dan server menunggu koneksi berikutnya. Dua program ini dapat dijalankan pada mesin yang sama. Jika dijalankan pada mesin berbeda, cukup ubah alamat “localhost” dengan suatu IP adress dari mesin di mana server dijalankan.


Server

import java.io.*;
import java.net.*;
public class Provider{
	ServerSocket providerSocket;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	Provider(){}
	void run()
	{
		try{
			//1. creating a server socket
			providerSocket = new ServerSocket(2004, 10);
			//2. Wait for connection
			System.out.println("Waiting for connection");
			connection = providerSocket.accept();
			System.out.println("Connection received from " + connection.getInetAddress().getHostName());
			//3. get Input and Output streams
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			sendMessage("Connection successful");
			//4. The two parts communicate via the input and output streams
			do{
				try{
					message = (String)in.readObject();
					System.out.println("client>" + message);
					if (message.equals("bye"))
						sendMessage("bye");
				}
				catch(ClassNotFoundException classnot){
					System.err.println("Data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				providerSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Provider server = new Provider();
		while(true){
			server.run();
		}
	}
}

Client

import java.io.*;
import java.net.*;
public class Requester{
	Socket requestSocket;
	ObjectOutputStream out;
 	ObjectInputStream in;
 	String message;
	Requester(){}
	void run()
	{
		try{
			//1. creating a socket to connect to the server
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			//2. get Input and Output streams
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			//3: Communicating with the server
			do{
				try{
					message = (String)in.readObject();
					System.out.println("server>" + message);
					sendMessage("Hi my server");
					message = "bye";
					sendMessage(message);
				}
				catch(ClassNotFoundException classNot){
					System.err.println("data received in unknown format");
				}
			}while(!message.equals("bye"));
		}
		catch(UnknownHostException unknownHost){
			System.err.println("You are trying to connect to an unknown host!");
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
		finally{
			//4: Closing connection
			try{
				in.close();
				out.close();
				requestSocket.close();
			}
			catch(IOException ioException){
				ioException.printStackTrace();
			}
		}
	}
	void sendMessage(String msg)
	{
		try{
			out.writeObject(msg);
			out.flush();
			System.out.println("client>" + msg);
		}
		catch(IOException ioException){
			ioException.printStackTrace();
		}
	}
	public static void main(String args[])
	{
		Requester client = new Requester();
		client.run();
	}
}

Penasaran? coba aja langsung!

  1. lanymeeladh
    13 August 2009 at 8:11 am

    berkunjuuunnng mas….
    makasiiiiiiiiiiiiiiihhh banyak….
    banyak info yg di dapet:-)
    semoga allah membalas dng yg lebih baik… amiennn:-)

  2. 13 August 2009 at 2:14 pm

    Java dari dulu mau belajar gak jadi jadi, tapi kayanya bahasa pemrogramannya susah yaaa

  3. 22 August 2009 at 2:19 am

    pak saya pengen banget bisa java, tapi kok kayaknya ga bisa2 yah? susah banget. apa trik nya? thx

  4. yudianto
    30 August 2009 at 1:52 am

    gimana sih caranya buat apilkasi client server, saya sangat tertarik dengan artikel ini. untuk lebih lanjut, dimana saya bisa dapet tutorialna untuk membuat server..
    makasi (^+^)..

  5. 14 October 2009 at 10:14 am

    cara cepat belajar java tu gimana caranya?

  6. arifin
    18 November 2009 at 3:17 pm

    kalau program bandwidth meter itu gimana source code nya yang pake java.
    trima kasih sebelumnya…

  7. sakde
    28 November 2009 at 1:26 pm

    masiHHH pusing, moga bisa membantu

    tHx

  8. mukit
    23 December 2009 at 5:04 am

    ada gak serverx yang bisa menerima koneksi lebih dari 1 client…..???
    lo’ ad,krm k emailku y…….

  9. Dj
    3 January 2010 at 5:05 am

    Lumayan………………….?Tapi terimah Kasih Lah?

  10. sandy
    24 January 2010 at 3:08 pm

    thank u.., brother…

  11. 14 March 2010 at 10:34 pm

    trimakasih atas Pembelajarannya…..

  12. AUGUSTA
    30 April 2010 at 5:20 pm

    MAKASIH BANGET…NIE PAS SEPERTI YANG AQ CARI,,,AQ ADA TUGAS JAVA…

    THANKZZ BANGETTTT….

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: