Showing posts with label Socket. Show all posts
Showing posts with label Socket. Show all posts

Monday, November 7, 2011

Simple Socket Programming

Hmm.. this is my task from my lecture
huuuft~ i think it's lil hard for looking for references and then i think i should share about it hehehe
and i hope it can help you guys..


the thing that u must do is creating the project and then creating the package.. the package here is named "progjar" hoho
and this is the source code..

package progjar;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class koneksi {


    private String content;


    public String koneksi(String url, String urn) {


            try {


            Socket socket = new Socket(url, 80);
            String isi;
            String header="";
            content="";
            InputStream is = socket.getInputStream();
            OutputStream os = socket.getOutputStream();


            String pesan = "GET "+ urn +" HTTP/1.0\r\nHOST: " + url + "\r\n\r\n";
            boolean isData = false;
            
            int c;
            String respon;
            os.write(pesan.getBytes());


            while((c = is.read()) > 0)
            {
                if((char)c!='\r' && isData==false)
                {
                    header+=(char)c;


                }
                else if((char)c=='\r' && isData==false)
                {
                    is.read();
                    c = is.read();
                    if((char)c=='\r')
                    {
                        is.read();
                        isData=true;
                    }
                    else
                    {   header+='\n';
                        header+=(char)c;
                    }
                }
                else if(isData==true)
                {
                    content += (char)c;
                }
                //System.out.print((char)c);
            }
            //System.out.print("ini adalah header" +header);
            //System.out.print("ini adalah content"+content);
            is.close();
            os.close();
            socket.close();


        }  catch (IOException ex) {
          System.out.println("gagal >.<");
        }
        return content;
    }
}
Read More
Powered by Blogger.