I have a small problem performing MemoryMappedFile streaming.
I have 2 projects, one for sending bytes and another for reading bytes. Between these two processes should be a 2 second sleep timer.
I've implemented all of this, but when the software attempts to do the read it appears to encounter a deadlock. The code for both processes is below.
Can anyone help me find the issue?
namespace ProcesComunication
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("AAB", 1024);
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryWriter bw = new BinaryWriter(mStream);
Mutex mx = new Mutex(true, "sync");
while (true)
{
Thread.Sleep(2000);
Console.WriteLine("TEST");
bw.Write(DateTime.Now.ToString());
mx.ReleaseMutex();
}
bw.Close();
mStream.Close();
}
}
}
namespace ProcesRead
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AAB");
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryReader br = new BinaryReader(mStream);
Mutex mx = Mutex.OpenExisting("sync");
while (true)
{
mx.WaitOne();
Console.Write(br.ReadString());
mx.ReleaseMutex();
}
br.Close();
mStream.Close();
}
}
}
I tried and found simple solution, below is a code:
Thanks to all contributors for answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.IO.MemoryMappedFiles;
namespace ProcesComunication
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("AAB", 1024);
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryWriter bw = new BinaryWriter(mStream);
Mutex mx = new Mutex(true, "sync");
while (true)
{
mx.WaitOne();
Thread.Sleep(2000);
var random = new Random();
var nextValue = random.Next().ToString();
Console.WriteLine(nextValue);
bw.Write(nextValue);
mx.ReleaseMutex();
}
bw.Close();
mStream.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.IO.MemoryMappedFiles;
namespace ProcesRead
{
class Program
{
static void Main(string[] args)
{
MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("AAB");
MemoryMappedViewStream mStream = mmf.CreateViewStream();
BinaryReader br = new BinaryReader(mStream);
Mutex emx = Mutex.OpenExisting("sync");
while (true)
{
Console.WriteLine(br.ReadString());
emx.WaitOne(2000);
}
br.Close();
mStream.Close();
}
}
}
There is no need to use a synchronization object (Mutex). MemoryMappedFile is thread safety between the processes. Don't use mutex. And control reader to it have data for reading.
Related
I'd like to restream the input http audio stream to as an rtsp stream from my local laptop. But for some reason the port wouldnt open on localhost. This is how I'm trying to do this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace VLC_test
{
class Program
{
static bool Terminate;
static bool Terminated;
static void Main(string[] args)
{
Thread t = new Thread(PlayMedia);
t.Start();
Console.ReadKey();
Terminate = true;
while (!Terminated) ;
}
static void PlayMedia()
{
Terminated = false;
FileInfo file = new FileInfo(#"C:\audio.mkv");
string httpStream = "http://10.254.255.10:8080/audio";
var libDirectory = new DirectoryInfo(#"C:\Program Files (x86)\VideoLAN\VLC\");
using (var mediaPlayer = new Vlc.DotNet.Core.VlcMediaPlayer(libDirectory))
{
var mediaOptions = new[]
{
":sout-avcodec-strict=-2",
":sout=#transcode{vcodec=none,acodec=mp4a,,ab=128,channels=2,samplerate=16000,scodec=none} :rtp{dst=127.0.0.1,port=5554,sdp=rtsp://127.0.0.1:5554/live}"
};
mediaPlayer.SetMedia(httpStream, mediaOptions);
mediaPlayer.Play(httpStream, mediaOptions);
while(!Terminate)
{
Thread.Sleep(10);
}
Terminated = true;
}
}
}
}
I would like my test laptop act as an RTSP server, but I cannot plugin as an argument "avcodec-strict=-2"
I started to learn about cryptography and I wanted to make my own file crypter.
After you run the program you must select file to encrypt and then stub. For now it is now encrypting but it is binding two files. After selecting this two files it will create file first.exe. Splitter string is for program to know where stub code ends and when original file code starts. It is made like this
stub
splitter (some string)
original file
When you run first.exe then it will create file cos.exe which should be the original file. But when i run it, it doesnt work. It shows "This app is not going to work on your computer" and it says that i need to find version for my OS.
Here is the code for crypter:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string stubpath, filepath;
private void Form1_Load(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
filepath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
stubpath = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
}
byte[] originalfile = File.ReadAllBytes(filepath);
byte[] array = Encoding.ASCII.GetBytes("password");
byte[] originalstubfile = File.ReadAllBytes(stubpath);
byte[] arr1 = Combine(array, originalfile);
ByteArrayToFile("first.exe", Combine(originalstubfile,arr1));
}
public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
try
{
using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
fs.Write(byteArray, 0, byteArray.Length);
return true;
}
}
catch (Exception ex)
{
return false;
}
}
public static byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
}
}
And here is the code for stub:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string exePath = Application.ExecutablePath;
byte[] originalfile = File.ReadAllBytes(exePath);
var str = System.Text.Encoding.Default.GetString(originalfile);
string[] tokens = str.Split(new[] { "password" }, StringSplitOptions.None);
//0 stub
//1 original file
byte[] toBytes = Encoding.ASCII.GetBytes(tokens[1]);
File.WriteAllBytes(System.AppDomain.CurrentDomain.BaseDirectory+ "cos.exe", toBytes);
}
}
}
EDIT:
Here is the error(Polish Language)
Also I found that when I delete splitter string and I dont use stub but I use 2 files like ex. putty.exe then it works, so I think that there is a problem in the stub.
Here is my code. I am codding a simple Socket test.
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using Microsoft.Win32;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Connexion au serveur 62.210.130.212");
using (client = new TcpClient("62.210.130.212", 35025))
using (NetworkStream networkStream = client.GetStream())
{
byte[] usernameBytes = Encoding.ASCII.GetBytes(username);
networkStream.Write(usernameBytes, 0, usernameBytes.Length);
}
while (true)
{
Byte[] data = new Byte[256];
Int32 bytes = networkStream.Read(data, 0, data.Length);
String responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("recieved: " + responseData);
}
}
}
}
Now the problem is that i can't use the networkStram anymore in my code because it has been deleted on the end of the using tab.
Can someone help me with that problem, I am new to C#, this doesn't exist in Java.
Thank you!
Julien.
You simply have to extend the using over all usages of the object you're using - this makes sense, if you just look at the word: All the code inside the curled brackets is using the object inside the brackets. So this should at least solve that specific problem:
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using Microsoft.Win32;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Connexion au serveur 62.210.130.212");
using (client = new TcpClient("62.210.130.212", 35025))
using (NetworkStream networkStream = client.GetStream())
{
byte[] usernameBytes = Encoding.ASCII.GetBytes(username);
networkStream.Write(usernameBytes, 0, usernameBytes.Length);
while (true)
{
Byte[] data = new Byte[256];
Int32 bytes = networkStream.Read(data, 0, data.Length);
String responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("recieved: " + responseData);
}
}
}
}
}
I am trying to create a new file with a specific length.
By using below code, the file gets created.
The problem is the length of the file created is 0kb's.
Also, the text under stream writer is not written in the file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
namespace Filesize
{
class Program
{
static void Main(string[] args)
{
FileInfo fi = new FileInfo(#"D:\\demotext2.txt");
StreamWriter sw = new StreamWriter(#"D:\\demotext2.txt", true);
try
{
while (fi.Length >= (2 * 1024 * 1024))
{
sw.WriteLine("Demo File");
}
}
catch (Exception ex)
{
ex.ToString();
}
}
}
}
Try to use this:
http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx
using (var fs = new FileStream(strCombined, FileMode.Create, FileAccess.Write, FileShare.None))
{
fs.SetLength(oFileInfo.FileSize);
}
Sorry if this is hard to understand, trying out C# for the first time.
I am trying to make a simple public 'chat' between clients that are connected to the server. I've tried passing integers to the server and printing them out and everything was fine, however,when I switched to strings, it seems that it can only pass 1 character (because of ns.Write(converted, 0, 1);). If I increase the ns.Write to ns.Write(converted,0,10) everything crashes (both the client and the server) when I enter a message that is less than 10 characters.
Server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
Console.WriteLine("Server started");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
client.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
byte[] buffer = new byte[10];
while (true)
{
NetworkStream ns = clientSocket.GetStream();
ns.Read(buffer,0,1);
string line = Encoding.UTF8.GetString(buffer);
Console.WriteLine(line);
}
}
}
}
Client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace Klientas
{
class Klientas
{
static void Main(string[] args)
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
NetworkStream ns = clientSocket.GetStream();
byte[] buffer = new byte[10];
string str = Console.ReadLine();
byte[] converted = System.Text.Encoding.UTF8.GetBytes(str);
ns.Write(converted, 0, 1);
}
}
}
}
You're best using the BinaryReader/BinaryWriter classes to correctly format and read out data. This removes the need to process it yourself. For example in the client do:
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
And in the server:
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
When using BinaryReader or BinaryWriter on the same stream, and you have .NET framework version 4.5 or above, be sure to leave the underlying stream open by using the overload:
using (var w = new BinaryWriter(stream, Encoding.UTF8, true)) {}