Send Image as binary data and string data via Socket programming in Play framework

Hello friends today we are going to see demo a simple example for sending binary data and string data via socket in play framework.

Application.java 

It defines the Controller for the application. its Provide web socket and send simple binary data from socket.


 

package controllers;

import play.*;
import play.mvc.*;

import views.html.*;
import models.*;

public class Application extends Controller {
   
    // render index page
    public static Result index() {
        return ok(index.render());
    }
   
    // get the ws.js script
    public static Result wsJs() {
        return ok(views.js.ws.render());
    }
   
    // Websocket interface
    public static WebSocket wsInterface(){
        return new WebSocket(){
           
            // called when websocket handshake is done
            public void onReady(WebSocket.In in, WebSocket.Out out){
                SimpleChat.start(in, out);
            }
        };  
    }  
}



Simplechat.java

It defines the socket listener for sending messages and receiving messages.
For Sending string data you just have to replace byte[] to String in both the files

package models;
import play.mvc.*;
import play.libs.*;
import play.libs.F.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.imageio.ImageIO;


public class SimpleChat{

    // collect all websockets here
    private static List> connections = new ArrayList>();
   
    public static void start(WebSocket.In in, WebSocket.Out out){
       
       
        File file = new File("C:\\Users\\saganlalp\\Pictures\\e.jpg");
       connections.add(out);
        in.onMessage(new Callback(){
            public void invoke(byte[] event){
                SimpleChat.notifyAll(event);
            }
        });
       
        in.onClose(new Callback0(){
            public void invoke(){
                //SimpleChat.notifyAll("A connection closed");
            }
        });
        try {

 /*FileInputStream imageInFile = new FileInputStream(file);
                    byte imageData[] = new byte[(int) file.length()];*/
                   
                  // server.getBroadcastOperations().sendEvent("fileevent", imageData);
                 
                  BufferedImage image = ImageIO.read(file);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "jpg", baos);
                byte[] byteArray = baos.toByteArray();
                /*OutputStream out = new BufferedOutputStream(new FileOutputStream("D:\\images\\new.jpg"));
                out.write(byteArray);
                if(out!=null){
                    out.close();
                }*/
               
                ByteBuffer buf = ByteBuffer.wrap(byteArray);
                       out.write(byteArray);
                    }
                     catch (IOException e) {
                      
                        e.printStackTrace();
                 }
           }
   
    // Iterate connection list and write incoming message
    public static void notifyAll(byte[] message){
        for (WebSocket.Out out : connections) {
            out.write(message);
        }
    }
   
   
}



Index.scala.html 

Its the index file of the application
 

@main("Small things jump around") {
    <section>
        <h1>Simple chat</h1>
       
        <input type="text" id="socket-input" />
        <div id="socket-messages"></div>
        <script type="text/javascript" charset="utf-8" src="@routes.Application.wsJs()"></script>
    </section>
}




main.scala.html

It is final file where data loads 


@(title: String)(content: Html)

<!DOCTYPE html>

<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <script src="@routes.Assets.at("javascripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
       
    </head>
    <body>
        @content
    </body>
</html>



ws.scala.js

Its js file that include Socket programming





$(function(){

    // get websocket class, firefox has a different way to get it
    var WS = window['MozWebSocket'] ? window['MozWebSocket'] : WebSocket;
   
    // open pewpew with websocket
    var socket = new WS('@routes.Application.wsInterface().webSocketURL(request)');
    socket.binaryType = "arraybuffer";
    var writeMessages = function(event){
        //$('#socket-messages').prepend(''+event.data+'
');
        //alert(event.data);
        if(event.data instanceof ArrayBuffer)
                        {
                        //alert(true);
                        showBinaryMessage(event);
                        }
        //$('#socket-messages').prepend('Red dot');
        //$('#socket-messages').prepend('
');
    }
    function showBinaryMessage(evt)
            {
                //alert("Hi this is my message"+evt);
               
                var binary = '';
                var bytes = new Uint8Array(evt.data);
                var i;
                for(i=0;i< bytes.byteLength; i++)
                    {
                    binary +=String.fromCharCode(bytes[i]);
                    }
                    //alert(i);
                    //alert(bytes);
                    //alert(binary);
                   
                $('#socket-messages').prepend('Red dot
');
            }
   
    socket.onmessage = writeMessages;
   
    $('#socket-input').keyup(function(event){
        var charCode = (event.which) ? event.which : event.keyCode ;
      
        // if enter (charcode 13) is pushed, send message, then clear input field
        if(charCode === 13){
            socket.send($(this).val());
            $(this).val('');   
        }
    });
});




Place e.jpg within the project directory or change the appropriate path of the image file

Just create new play project , copy this files in appropriate directory .
run the play project , your example for socket programming is ready





Enter your email address:
Delivered by FeedBurner

1 comment:

Admin said...

Hi Thanks for posting this.
Can you please put the route file also for this project? btw, which version of play this is written on?