Click here to Skip to main content
6,287,838 members and growing! (16,291 online)
Email Password   helpLost your password?
Languages » Java » General License: The Code Project Open License (CPOL)

Using Sockets in Java - Server

By Marius Iulian Mihailescu

Creating a server program using Java
Java
Version:2 (See All)
Posted:24 Mar 2008
Views:7,884
Bookmarked:5 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
5 votes for this article.
Popularity: 2.10 Rating: 3.00 out of 5
2 votes, 40.0%
1

2
1 vote, 20.0%
3

4
2 votes, 40.0%
5

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:
    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:
    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:
    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:

    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:
    output.println("Awaiting data...");
    String input = input.nextLine();
  5. Close the connection (after completion of the dialogue):
    link.close();

Look at this code :

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)

About the Author

Marius Iulian Mihailescu


Member

Occupation: Software Developer
Company: Q'Net International
Location: Romania Romania

Other popular Java articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
General[Message Deleted] Pinmemberit.ragester22:56 2 Apr '09  
GeneralWho cares about Java? PinsupporterMark Nischalke12:00 24 Mar '08  
GeneralRe: Who cares about Java? PinmemberDerek Bartram14:16 24 Mar '08  
GeneralRe: Who cares about Java? PinmemberIulian Marius15:10 24 Mar '08  
GeneralRe: Who cares about Java? PinmemberDerek Bartram23:14 24 Mar '08  
GeneralRe: Who cares about Java? PinmemberOwen Lawrence4:17 25 Mar '08  
AnswerRe: Who cares about Java? [modified] PinmemberMarius Iulian Mihailescu5:47 25 Mar '08  
GeneralRe: Who cares about Java? PinmemberSyed M Hussain13:31 5 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Mar 2008
Editor: Deeksha Shenoy
Copyright 2008 by Marius Iulian Mihailescu
Everything else Copyright © CodeProject, 1999-2009
Beta | Advertise on the Code Project