Network Connection

Setting a network connection in JAVA is very easy. Today we will explain how to connect to a server, send a simple request to this server and read the response.

In this example, we are using the class to connect to the host We are connecting to the port 80, because this is the TCP port commonly used by the HTTP protocol.

Then, after opening the output stream, we are sending a HTTP GET request:

s_out.println("GET / HTTP/1.1");
s_out.println("Host: " + host + ":80");

The format of the GET request is as follows:

GET <requested resource> <HTTP version>

Requested resource can be, for instance, an image on the page. In our example, we are simply requesting the source code of the page.

Java network connection code


public class SimpleSocket
	public static void main(String [] args)
		String host = "";
		int port = 80;

		PrintWriter s_out = null;
		BufferedReader s_in = null;

		System.out.println("Connecting to " + host + " on port " + port);
		Socket socket;

		try {
			socket = new Socket(host, port);

			System.out.println("Just connected to "
					+ socket.getRemoteSocketAddress());

			//Sending request
			s_out = new PrintWriter( socket.getOutputStream(), true);         

			s_out.println("GET / HTTP/1.1");
			s_out.println("Host: " + host + ":80");

			System.out.println("Message send!");

			s_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

			//Getting response 
			System.out.println("Response from itcuties:\n");
			String response;
			while ((response = s_in.readLine()) != null) 
				System.out.println( response );

			//Closing the i/o streams

			//Closing the socket

		} catch (UnknownHostException e) {
		} catch (IOException e) {

It is important to specify the host one more time while sending the message.

The server receives following message:

GET / HTTP/1.1

Server responds with a HTTP response:

HTTP/1.0 200 OK

This is a standard answer for successful HTTP requests. Then it will send some information about the host (the data of the last modification etc.) and the source code that we requested. We are retrieving this information from the input stream and printing them on the console.

One Response to "Network Connection"

  1. tolga says:

    How we can copy to text file all gotten information ?


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>