Click here to Skip to main content
14,607,948 members

Motion JPEG Streaming Server

Rate this:
4.99 (64 votes)
Please Sign up or sign in to vote.
4.99 (64 votes)
23 Apr 2012CPOL
Implementing a MJPEG (or Motion JPEG) streaming server that can be used to steam screenshots or any other source of images over the HTTP protocol to any web browser client (MJPEG stream writer is included in the library)

For mobile clients:

Samsung Galaxy SII

Other clients (such as Firefox, Chrome and VLC player):

Streaming the desktop images to different remote clients

Introduction

Motion JPEG is a stream of JPG images over HTTP protocol and it is commonly used for many multimedia applications specially in digital cameras (IP cameras). Although there are many ways to send images as a video to any remote computer, MJPEG is the preferred one since normally it does not need any client software to be installed on the remote computer! That is because it is supported by most of the common web browsers like Firefox and Chrome but unfortunately, it is not yet supported by Internet Explorer directly (but there are some plug-ins that make it possible to work with Internet Explorer).

Motivation

In many, I needed to stream a video of my desktop, camera, or whatever to a remote computer which has no client software to see my stream... In such a case, using Motion-JPEG streams is preferred because it needs no more than an internet browser. In this article, I'm not going to describe the internal structure of an MJPEG stream (for more information, please visit Motion_JPEG). Instead of that, I'm going to describe how to use this library for MJPEG streaming.

How to Use This Library

The main class in our library is ImageSreamingSever() which contains the following methods and properties:

Methods

  • void Start(): Starts the server on a specified TCP port
  • void Stop(): Stops the server and closes any open connections

Properties

  • ImagesSource: The images collection (IEnumerable<Image>) to be streamed to any connected client
  • Interval: The delay time (in milliseconds) between each sending image from the ImagesSource collection
  • IsRunning: Is a read-only bool property indicating the status of the server
  • Clients: Returns a read-only collection of the currently connected socket of each client

Example

In order to implement a streaming server that can send a video of your desktop screen to any connected client, you'll need only two lines of code using our ImageStreamingServer, as follows:

ImageStreamingServer server = new ImageStreamingServer(); 
server.Start(8080);

That's it !!!

Now if you open (for example) the Chrome Internet Explorer and write the IP of the server followed by colon and then the port number, in our example, it is something like this...

http://127.0.0.1:8080

...you will properly see a video of your computer screen in the explorer... and same if you do this from another computer (with the correct IP of your server), you should see something like this:

Google Chrome

Implementing Your Own ImagesSource

Actually, I've chosen IEnumerable<Image> as a source of images because of the flexibility that this interface is providing, for example, the default ImagesSource property of the class ImageStreamingServer is an IEnumerable<Image> of the desktop screen, but at the same time, you are free to implement any other type of image source you like by changing the value of that property.

Suppose you want to make the images source from the camera or from the images file of any folder in your computer, then your code should be something like this:

IEnumerable<Image> CameraImagesSource() 
{ 
    // Your code must be here 
} 

IEnumerable<Image> FolderImagesSource(string path) 
{ 
    // Your code must be here 
}

As a real example, let's implement a source of images that streams all "*.jpg" photos from a specified folder path as follows:

private IEnumerable<Image> FolderImagesSource(string path)
{
    var files = System.IO.Directory.GetFiles(path, "*.jpg");

    foreach (var file in files)
        yield return Image.FromFile(file);

    yield break;
}

private void Form1_Load(object sender, EventArgs e)
{
    var source = FolderImagesSource(@"C:\Pictures\");

    _Server = new ImageStreamingServer();
    _Server.ImagesSource = source;
    _Server.Start(8080);
}

Note: The above code can be shortened as follows (thanks to IEnumerable extensions and LINQ):

var source = System.IO.Directory.GetFiles(@"C:\Pictures\", "*.jpg").Select(s => Image.FromFile(s));

_Server = new ImageStreamingServer(source);
_Server.Start(8080);

Supported Client Software

To see the streaming video of our server, you will need to use any software that supports Motion-JPEG streaming such as a Mozilla Firefox, Google's Chrome or VideoLAN Player (VLC):

Free client software for Windows PC

And finally, for your mobile (Android), use FireFox or any other free app that can be found on Google's market such as tinyCamMonitor (that was used in the picture below):

Samsung Galaxy SII

Future Versions

In the future versions of the library, I'm going to add a variety of image sources such as:

  • Images from a specific region of the screen
  • Images from a specific window in the system
  • Streaming images from a camera
  • All photos from any folder in a disk
  • And any other suggested sources of images you may want !? ...

And till that time, feel free to enjoy this version. ;-)

History

  • 23rd April, 2012: Initial version

License

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

Share

About the Author

Ragheed Al-Tayeb
Team Leader Hawk International for Finance & Construction Ltd.
Yemen Yemen
Bachelor degree of Computer Sciences, Software developer using .NET (Visual Basic & C#).
I like the development of an Artificial Intelligence Systems, GPS Applications, GDI+, APIs, N-Tier Applications, Distributed Systems and Network Monitoring Systems.
Mobile Development (Windows Mobile & Android).

Comments and Discussions

 
GeneralRe: How to run the ImageStreamingServer on a website Pin
franva0085-Mar-14 5:31
Memberfranva0085-Mar-14 5:31 
GeneralRe: How to run the ImageStreamingServer on a website Pin
KL Lawingco1-Dec-15 6:43
MemberKL Lawingco1-Dec-15 6:43 
Question"I Am Making Software To Remote Other Desktop And I Am Get Help Of Your Rtavideostreamer Code Of C# , I Implement It Successfully Without Error But I Get Client Count Is 0 Then What I Do....Please...": Pin
Member 1052710517-Jan-14 18:14
MemberMember 1052710517-Jan-14 18:14 
QuestionDo you know why it caused crash on Firefox (version 26) after 20 min? Pin
xmans7-Jan-14 19:13
Memberxmans7-Jan-14 19:13 
QuestionHuge memory leaks Pin
Daddy_leo200116-Dec-13 1:50
MemberDaddy_leo200116-Dec-13 1:50 
AnswerRe: Huge memory leaks Pin
xmans7-Jan-14 16:54
Memberxmans7-Jan-14 16:54 
AnswerRe: Huge memory leaks Pin
Shiine5-Jan-17 9:48
MemberShiine5-Jan-17 9:48 
QuestionNullReferenceExeption Pin
Андрей Корниенко15-Dec-13 22:50
MemberАндрей Корниенко15-Dec-13 22:50 
Hi!
I have a little problem with your code. I'm confused. When I call your code, project starts normally, but after some time, when I trying tipe some text into any window, like IM, app will be crashed and IDE show me point into Main method.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Program.MainForm = new MainForm();
Application.Run(Program.MainForm); // here

I tried change attribute [STAThread] for [MTAThread], but it doesn't work.
And your code I use just like copy and paste. I change just namespace.
I have no idea, what need to say you more about my problem.
That's output of my program:
Server started on port 8080.
New client from 192.168.0.127:38396
System.Transactions Critical: 0 : <TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Critical"><TraceIdentifier>http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/Unhandled</TraceIdentifier><Description>Необработанное исключение</Description><AppDomain>ScreenBlocker.exe</AppDomain><Exception><ExceptionType>System.NullReferenceException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>В экземпляре объекта не задана ссылка на объект.</Message><StackTrace>   в System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG&amp; msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove)
   в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.Run(Form mainForm)
   в ScreenBlocker.Program.Main(String[] args) в d:\SharpDevelop Projects\ScreenBlocker\ScreenBlocker\Program.cs:строка 30</StackTrace><ExceptionString>System.NullReferenceException: В экземпляре объекта не задана ссылка на объект.
   в System.Windows.Forms.UnsafeNativeMethods.PeekMessage(MSG&amp; msg, HandleRef hwnd, Int32 msgMin, Int32 msgMax, Int32 remove)
   в System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   в System.Windows.Forms.Application.Run(Form mainForm)
   в ScreenBlocker.Program.Main(String[] args) в d:\SharpDevelop Projects\ScreenBlocker\ScreenBlocker\Program.cs:строка 30</ExceptionString></Exception></TraceRecord>

Have you any ideas, what's can be wrong with my code?

P. s. Ok. I really tired now.
How I can use that code with any other?

modified 16-Dec-13 8:24am.

Bug_Server.Stop(); Pin
ktkachenko2-Sep-13 2:54
Memberktkachenko2-Sep-13 2:54 
QuestionVideo files stream mp4 Pin
iskender7731-Aug-13 23:18
Memberiskender7731-Aug-13 23:18 
QuestionGreat and succinct article! Need one more feature to make it perfect Pin
franva00822-Aug-13 16:06
Memberfranva00822-Aug-13 16:06 
QuestionSpecific Window Pin
Member 1020733713-Aug-13 6:41
MemberMember 1020733713-Aug-13 6:41 
GeneralMy vote of 5 Pin
drazen129-Aug-13 1:41
Memberdrazen129-Aug-13 1:41 
GeneralMy vote of 3 Pin
Mic8-Aug-13 15:01
MemberMic8-Aug-13 15:01 
BugDoes not works in IE Pin
Singh Vijay Kumar24-Jul-13 18:56
professionalSingh Vijay Kumar24-Jul-13 18:56 
GeneralRe: Does not works in IE Pin
Ragheed Al-Tayeb25-Jul-13 20:03
MemberRagheed Al-Tayeb25-Jul-13 20:03 
Questionhi Pin
Jtmaroor26-Jun-13 22:48
MemberJtmaroor26-Jun-13 22:48 
GeneralMy vote of 5 Pin
Jtmaroor26-Jun-13 22:45
MemberJtmaroor26-Jun-13 22:45 
QuestionEmbedded Streaming Pin
Paul Philip Daniels21-Jun-13 8:07
MemberPaul Philip Daniels21-Jun-13 8:07 
QuestionAbout MJPEG Streaming Server Pin
Member 998370612-Apr-13 6:02
MemberMember 998370612-Apr-13 6:02 
QuestionVideo Streaming Pin
Fábio Pinho29-Mar-13 4:30
MemberFábio Pinho29-Mar-13 4:30 
AnswerRe: Video Streaming Pin
joshua53679-Apr-13 20:44
Memberjoshua53679-Apr-13 20:44 
GeneralRe: Video Streaming Pin
Fábio Pinho9-Apr-13 22:19
MemberFábio Pinho9-Apr-13 22:19 
AnswerRe: Video Streaming Pin
Rahul Kumar12-Jun-14 1:16
MemberRahul Kumar12-Jun-14 1:16 
BugError when Call Stop() Pin
Hong Thai8-Mar-13 5:41
MemberHong Thai8-Mar-13 5:41 

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.

Article
Posted 23 Apr 2012

Tagged as

Stats

360.2K views
39.7K downloads
135 bookmarked