Sending and Receiving Messages Using WebSocket

Sending and Receiving Messages Using WebSocket
With WebSocket, Endpoints classes extension can send and receive text and binary messages. In addition, they can also send ping frames and receive pong frames.
Java websockets contains Session and RemoteEndpoint interfaces which are use to send messages and also establish connections with peer using OnMessage annotation to receive messages from it.

Key points to note in WebSocket EndPoint lifecycle
1. Connection establishment ; To establish connection, there is a need to note the starting session and also configure the connection with the server

which can be represented as below

@OnOpen
public void open ( Session session,EndpointConfig conf )
{
...
}

2. Sending and receiving message

@OnMessage
public void message ( Session session, String message )
{

...

}

3. Handling errors while sending or receiving messages

@OnError
public void error ( Session session, Throwable error )

{

...
}

4. Close connection when the user is not sending or receiving message

@OnClose

public void close( Session session, CloseReason close )
{
...

}

To Send and Receive Message

@ServerEndPoint("/send")
public class SendFromEndPoint
{

    @OnMessage

    public void message ( Session session , String message )

    {

        try
        {
            for ( Session mySession : session.getSession() );
            {

                if ( mySession.isOpen() )

                {

                    mySession.getBsicRemote().sendMessage(message);

                }
            }

             catch ( Exception error)
            {
                errr.printStackTrace();
            }


        }


    }

}

To Receive Message

@ServerEndpoint("/receive")
public class ReceiveFromEndpoint {
    @OnMessage
    public void textMessage(Session session, String msg) {
        System.out.println("Text message: " + msg);
    }
    @OnMessage
    public void binaryMessage(Session session, ByteBuffer msg) {
        System.out.println("Binary message: " + msg.toString());
    }
    @OnMessage
    public void pongMessage(Session session, PongMessage msg) {
        System.out.println("Pong message: " +
                msg.getApplicationData().toString());
    }
}
Advertisements

One thought on “Sending and Receiving Messages Using WebSocket

Add yours

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

Blog at WordPress.com.

Up ↑

%d bloggers like this: