Click here to Skip to main content
15,867,330 members
Articles / Mobile Apps / Android

Using Sockets in Java - Server

Rate me:
Please Sign up or sign in to vote.
3.60/5 (10 votes)
3 Mar 2013CPOL2 min read 75.2K   1.4K   25   16
Creating a server program using Java

Introduction

In this article, I will describe the steps to make a connection in Java using Sockets. Let's start to understand what is a communication created via TCP/IP... A communication link created via TCP/IP sockets is a connection-oriented link. This means that the connection between the server and client remains open throughout the duration of the dialogue between the two and is only broken (under normal circumstances) when one end of the dialogue formally terminates the exchanges (via an agreed protocol).

Using the Code

  1. Create a ServerSocket object:
    Java
    ServerSocket mySock = new ServerSocket(1234);

    Here the server will wait ("listen for") a connection from a client on port 1234.

  2. Put the server into a waiting state:
    Java
    Socket link = mySock.accept();

    Here the server waits indefinitely("blocks") for a client to connect with the help of accept method of class ServerSocket, class that will return a Socket object when a connection is made.

  3. Set up input and output streams.
    Let's examine two methods: getInputStream and getOuputStream of class Socket. These methods are used to get references to streams associated with the socket returned in step 2.
    You will use these streams later for communication with a client that has just made a connection. If you are not using a GUI application, you can wrap a Scanner object around the InputStream object, object that is returned by method getInputStream, in order to obtain string-oriented input, let's see how:
    Java
    Scanner input = new Scanner(link.getInputStream());

    At the same time, we can wrap a PrintWriter object around the OutputStream object returned by method getOutputStream. We supply the PrintWriter constructor with a second argument of true. This argument will cause the output buffer to be flushed for every call of println, let's see how:

    Java
    PrintWriter output = new PrintWriter(link.getOutputStream(),true);
  4. Send and receive data.
    After you have set up your Scanner and PrintWriter objects, to send data and to receive is very straightforward. For this, we have to use nextLine method for receiving data and println to send data, let's see how:
    Java
    output.println("Awaiting data...");
    String input = input.nextLine();
  5. Close the connection (after completion of the dialogue):
    Java
    link.close();

Look at this code :

Java
public class TCPEchoServer
{
    private static ServerSocket servSock;
    private static final int PORT = 1234;

    public static void main(String[] args)
    {
        System.out.println("Opening port...\n");
        try
        {
            servSock = new ServerSocket(PORT);      //Step 1.
        }
        catch(IOException ioEx)
        {
            System.out.println("Unable to attach to port!");
            System.exit(1);
        }
        do
        {
            handleClient();
        }
        while (true);
    }

    private static void handleClient()
    {
        Socket link = null;                     			//Step 2.
        try
        {
            link = servSock.accept();        				//Step 2.

            Scanner input = new Scanner(link.getInputStream()); 	//Step 3.
            PrintWriter output =
		    new PrintWriter(link.getOutputStream(),true); 	//Step 3.

            int numMessages = 0;
            String message = input.nextLine();      			//Step 4.
            while (!message.equals("***CLOSE***"))
            {
                System.out.println("Message received.");
                numMessages++;
                output.println("Message " +
		        numMessages + ": " + message);   		//Step 4.
                message = input.nextLine();
            }
            output.println(numMessages + " messages received."); 	//Step 4.
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }
        finally
        {
            try
            {
                System.out.println( "\n* Closing connection... *");
                link.close();                    //Step 5.
            }
            catch(IOException ioEx)
            {
                System.out.println("Unable to disconnect!");
                System.exit(1);
            }
        }
    }
}

History

This example represents the SERVER program. In the next article (JavaSocketsClient.aspx), I will describe the CLIENT program, which is almost the same.

History

  • 24th March, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionusage Pin
sebuliba_f27-Jun-14 3:22
sebuliba_f27-Jun-14 3:22 
AnswerRe: usage Pin
Marius Iulian Mihailescu28-Jun-14 5:21
professionalMarius Iulian Mihailescu28-Jun-14 5:21 
GeneralRe: usage Pin
sebuliba_f30-Jun-14 2:23
sebuliba_f30-Jun-14 2:23 
GeneralMy vote of 5 Pin
Member 432084414-Mar-13 12:00
Member 432084414-Mar-13 12:00 
GeneralMy vote of 5 Pin
yichangzyh6-Mar-13 14:31
yichangzyh6-Mar-13 14:31 
GeneralMy vote of 5 Pin
Santhoshpettacode3-Mar-13 6:46
professionalSanthoshpettacode3-Mar-13 6:46 
QuestionNot really an article... Pin
Dave Kreskowiak3-Mar-13 4:16
mveDave Kreskowiak3-Mar-13 4:16 
GeneralMy vote of 5 Pin
Member 432084430-Sep-11 3:38
Member 432084430-Sep-11 3:38 
General[Message Deleted] Pin
it.ragester2-Apr-09 21:56
it.ragester2-Apr-09 21:56 
QuestionWho cares about Java? Pin
Not Active24-Mar-08 11:00
mentorNot Active24-Mar-08 11:00 
AnswerRe: Who cares about Java? Pin
Derek Bartram24-Mar-08 13:16
Derek Bartram24-Mar-08 13:16 
GeneralRe: Who cares about Java? Pin
Marius Iulian Mihailescu24-Mar-08 14:10
professionalMarius Iulian Mihailescu24-Mar-08 14:10 
GeneralRe: Who cares about Java? Pin
Derek Bartram24-Mar-08 22:14
Derek Bartram24-Mar-08 22:14 
GeneralRe: Who cares about Java? Pin
Owen Lawrence25-Mar-08 3:17
Owen Lawrence25-Mar-08 3:17 
AnswerRe: Who cares about Java? [modified] Pin
Marius Iulian Mihailescu25-Mar-08 4:47
professionalMarius Iulian Mihailescu25-Mar-08 4:47 
AnswerRe: Who cares about Java? Pin
Syed M Hussain5-May-08 12:31
Syed M Hussain5-May-08 12:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.