No feed back error message web socket in c# - c#

I am use this code in console. in console I can get error message but if I use same code in desktop form no error message coming
In Console
using (var ws = new WebSocket("ws://localhost:5000/mw"))
{
// Set the WebSocket events.
string indata = "{\"Event\":\"TRANSACTION\",\"Operation\":\"GET_MERCHANT_INFO\"}";
ws.OnOpen += (ss, ee) => ws.Send(indata);
\\Problam is here --->
ws.OnMessage += (ss, ee) => {
var fmt = "[WebSocket Message] {0}";
var body = !ee.IsPing ? ee.Data : "A ping was received.";
Console.WriteLine(fmt, body);
};
---->
ws.OnError += (ss, ee) => {
var fmt = "[WebSocket Error] {0}";
Console.WriteLine(fmt, ee.Message);
};
ws.OnClose += (ss, ee) => {
var fmt = "[WebSocket Close ({0})] {1}";
Console.WriteLine(fmt, ee.Code, ee.Reason);
};
ws.Connect();
windows Form
ws.OnOpen += (ss, ee) => ws.Send(data);
ws.OnMessage += (ss, ee) => {
var fmt = "[WebSocket Message] {0}";
var body = !ee.IsPing ? ee.Data : "A ping was received.";
listBox1.Items.Add(string.Format(fmt, body));
Thanks
I tried many times

Related

Real-Tine transcription

I am playing with the real-time conversation
and I get this error
IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
SocketException: An existing connection was forcibly closed by the remote host.
could somebody help me, please
public static async Task TranscribeConversationsAsync(string voiceSignatureStringUser1, string voiceSignatureStringUser2)
{
var filepath = "Tech.wav";
var config = SpeechConfig.FromSubscription(VoiceGenerator.subscriptionKey, VoiceGenerator.region);
config.SetProperty("ConversationTranscriptionInRoomAndOnline", "true");
// en-us by default. Adding this code to specify other languages, like zh-cn.
// config.SpeechRecognitionLanguage = "zh-cn";
var stopRecognition = new TaskCompletionSource<int>();
using (var audioInput = AudioConfig.FromWavFileInput(filepath))
{
var meetingID = Guid.NewGuid().ToString();
using (var conversation = await Conversation.CreateConversationAsync(config, meetingID))
{
// create a conversation transcriber using audio stream input
using (var conversationTranscriber = new ConversationTranscriber(audioInput))
{
conversationTranscriber.Transcribing += (s, e) =>
{
Console.WriteLine($"TRANSCRIBING: Text={e.Result.Text} SpeakerId={e.Result.UserId}");
};
conversationTranscriber.Transcribed += (s, e) =>
{
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
Console.WriteLine($"TRANSCRIBED: Text={e.Result.Text} SpeakerId={e.Result.UserId}");
}
else if (e.Result.Reason == ResultReason.NoMatch)
{
Console.WriteLine($"NOMATCH: Speech could not be recognized.");
}
};
conversationTranscriber.Canceled += (s, e) =>
{
Console.WriteLine($"CANCELED: Reason={e.Reason}");
if (e.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={e.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails={e.ErrorDetails}");
Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
stopRecognition.TrySetResult(0);
}
};
conversationTranscriber.SessionStarted += (s, e) =>
{
Console.WriteLine($"\nSession started event. SessionId={e.SessionId}");
};
conversationTranscriber.SessionStopped += (s, e) =>
{
Console.WriteLine($"\nSession stopped event. SessionId={e.SessionId}");
Console.WriteLine("\nStop recognition.");
stopRecognition.TrySetResult(0);
};
// Add participants to the conversation.
var speaker1 = Participant.From("User1", "en-US", voiceSignatureStringUser1);
var speaker2 = Participant.From("User2", "en-US", voiceSignatureStringUser2);
await conversation.AddParticipantAsync(speaker1);
await conversation.AddParticipantAsync(speaker2);
// Join to the conversation and start transcribing
await conversationTranscriber.JoinConversationAsync(conversation);
await conversationTranscriber.StartTranscribingAsync().ConfigureAwait(false);
// waits for completion, then stop transcription
Task.WaitAny(new[] { stopRecognition.Task });
await conversationTranscriber.StopTranscribingAsync().ConfigureAwait(false);
}
It appears that something is blocking my connection, but why? I Searched of google, but I only find reference for ASP, not for console apps

Azure timestamps not appearing in speech to text model?

Timestamps are not appearing in my results when I run my speech-to-text Azure model. I'm not getting any errors, but also not getting timestamped results. My code is:
using System;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace SUPRA
{
internal class NewBaseType
{
static async Task Main(string[] args)
{
// Creates an instance of a speech config with specified subscription key and region.
// Replace with your own subscription key and service region (e.g., "westus").
var config = SpeechConfig.FromSubscription("8ec6730993d54cf9a9cec0f5d08b8e8b", "eastus");
// Generates timestamps
config.OutputFormat = OutputFormat.Detailed;
config.RequestWordLevelTimestamps();
//calls the audio file
using (var audioInput = AudioConfig.FromWavFileInput("C:/Users/MichaelSchwartz/source/repos/AI-102-Process-Speech-master/transcribe_speech_to_text/media/narration.wav"))
// Creates a speech recognizer from microphone.
using (var recognizer = new SpeechRecognizer(config, audioInput))
{
recognizer.Recognized += (s, e) =>
{
var result = e.Result;
if (result.Reason == ResultReason.RecognizedSpeech)
{
Console.WriteLine(result.Text);
}
};
recognizer.Recognized += (s, e) =>
{
var j = e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult);
};
recognizer.Canceled += (s, e) =>
{
Console.WriteLine($"\n Canceled. Reason: {e.Reason.ToString()}, CanceledReason: {e.Reason}");
};
recognizer.SessionStarted += (s, e) =>
{
Console.WriteLine("\n Session started event.");
};
recognizer.SessionStopped += (s, e) =>
{
Console.WriteLine("\n Session stopped event.");
};
// Starts continuous recognition.
// Uses StopContinuousRecognitionAsync() to stop recognition.
await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
do
{
Console.WriteLine("Press Enter to stop");
} while (Console.ReadKey().Key != ConsoleKey.Enter);
// Stops recognition.
await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
}
}
}
}
No errors are returned and the results are accurate but without timestamps. I've included the code to produce timestamps in lines 37-40. How do I get timestamps to generate? Thanks.
You configured correctly but seems you haven't print the result in the console. Just try the code below:
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System;
using System.Threading.Tasks;
namespace STTwithTime
{
class Program
{
static void Main(string[] args)
{
var key = "";
var region = "";
var audioFilePath = #"";
var speechConfig = SpeechConfig.FromSubscription(key, region);
// Generates timestamps
speechConfig.RequestWordLevelTimestamps();
speechConfig.OutputFormat = OutputFormat.Detailed;
var stopRecognition = new TaskCompletionSource<int>();
var audioConfig = AudioConfig.FromWavFileInput(audioFilePath);
var recognizer = new SpeechRecognizer(speechConfig, audioConfig);
//Display Recognizing
recognizer.Recognizing += (s, e) =>
{
Console.WriteLine($"RECOGNIZING:{e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult)}");
};
//Display Recognized
recognizer.Recognized += (s, e) =>
{
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
Console.WriteLine($"RECOGNIZED :{e.Result.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult)}");
}
else if (e.Result.Reason == ResultReason.NoMatch)
{
Console.WriteLine($"NOMATCH: Speech could not be recognized.");
}
};
recognizer.Canceled += (s, e) =>
{
Console.WriteLine($"CANCELED: Reason={e.Reason}");
if (e.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={e.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails={e.ErrorDetails}");
Console.WriteLine($"CANCELED: Did you update the subscription info?");
}
stopRecognition.TrySetResult(0);
};
recognizer.SessionStopped += (s, e) =>
{
Console.WriteLine("\n Session stopped event.");
stopRecognition.TrySetResult(0);
};
recognizer.StartContinuousRecognitionAsync().GetAwaiter().GetResult();
// Waits for completion. Use Task.WaitAny to keep the task rooted.
Task.WaitAny(new[] { stopRecognition.Task });
}
}
}
Result
Display recognizing:
Display recognized:

C# BackgroundWorker inside BackgroundWorker

I'm facing an issue with BackgroundWorker in C#, hope you can help.
Here are some piece of code on my program
var bwBIG = new BackgroundWorker();
bwBIG.DoWork += (_senderBIG, argsBIG) =>
{
var bw = new BackgroundWorker();
String requestResult = "";
bw.DoWork += (_sender, args) =>
{
requestResult = tempHelper.GetData();
};
bw.RunWorkerCompleted += (_sender, args) =>
{
makeData(requestResult);
};
bw.RunWorkerAsync();
}; //bwBIG.DoWork
bwBIG.RunWorkerCompleted += (_senderBIG, argsBIG) =>
{
prepareData(rtbData.Text);
MessageBox.Show("Data OK");
};
bwBIG.RunWorkerAsync();
It suppose to run the tempHelper.GetData() , and then makeData(requestResult), and then finnally prepareData(rtbData.Text) then MessageBox.Show("Data OK");
However, it seems the bw is not running at all, whenever I run the code, it just jumped strange to MessageBox.Show("Data OK");
Any help please???
Thanks for reading.
It's kinda useless to create backgroundworkerthread inside a worker thread.
I would keep it this way:
var localCopy = rtbData.Text;
var bwBIG = new BackgroundWorker();
bwBIG.DoWork += (_senderBIG, argsBIG) =>
{
var requestResult = tempHelper.GetData();
makeData(requestResult);
prepareData(localCopy);
MessageBox.Show("Data OK");
}; //bwBIG.DoWork
bwBIG.RunWorkerAsync();
It's kinda hard to see the flow of data.

WebSocket Reconnect issue on network disconnection

i am using below socket functions to receive data from socket server, when i disconnect my network connection , and reconnect again socket application stop receiving data. I also tried to add a timer which check the state of socket every 20 sec but its not working. Any advise?
private WebSocket client; //before form_load
private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host);
client.OnOpen += (ss, ee) =>
{
MessageBox.Show(string.Format("Connected to {0} successfully ", host));
};
client.OnError += (ss, ee) =>
{
MessageBox.Show(" Error: " + ee.Message);
};
client.OnMessage += (ss, ee) =>
{
MessageBox.Show("Message: " + ee.Message);
};
client.OnClose += (ss, ee) =>
{
MessageBox.Show(string.Format("Disconnected with {0}", host));
};
client.Connect();
}
private void timer1_Tick(object sender, EventArgs e)
{
if(client.ReadyState.ToString()=="Closed")
{
client.Close();
client = new WebSocket(host);
client.Connect();
}
}
You didn't mention the web socket library/package you used. Here is a simple working reconnect example using WebSocket4Net.
Because of AutoSendPing it closes the connection when something happens to the network and timer tries to reconnect if the socket is closed.
private WebSocket client;
private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host)
{
EnableAutoSendPing = true,
AutoSendPingInterval = 10,
};
client.Opened += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Connected");
};
client.Error += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Error {ee.Exception}");
};
client.MessageReceived += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Message: {ee.Message}");
};
client.Closed += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Disconnected");
};
client.Open();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (client.State == WebSocketState.Closed)
{
client.Open();
System.Diagnostics.Debug.WriteLine("Trying to reconnect by timer");
}
}

Redirecting STD error & STDOut

I am currently having issues redirecting both STDError and STDOutput. What I want to do is when there is an error to be printed to a rich text box along with normal output if no error is thrown.
The issue I am having is that if I add the line to redirect the SDT Error:
string error = process1.StandardError.ReadToEnd();
rchsdtOut.Text = error;
Then my normal STD Out doesn't redirect to the text fild, but if there is an error that is printed.
process1 = new System.Diagnostics.Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.RedirectStandardError = true;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.FileName = "java.exe ";
//String abc = txtSingleBar.Text.Replace("\\", "/");
toLoad = lstBarToLoad.Items[i].Text;
process1.StartInfo.Arguments = "-Xmx512M -jar";
process1.StartInfo.Arguments += toLoad;
Console.WriteLine(process1.StartInfo.Arguments);
try
{
process1.Start();
process1.OutputDataReceived += (s, a) => myMethod(a);
process1.BeginOutputReadLine();
string error = process1.StandardError.ReadToEnd();
rchsdtOut.Text = error;
}
Method to write events to a text fild
private void myMethod(DataReceivedEventArgs e)
{
if (e.Data != null)
{
Action action = () => rchsdtOut.Text += "\r\n" + e.Data.ToString();
rchsdtOut.BeginInvoke(action, null);
Console.WriteLine(e.Data.ToString());
}
}//end of private
Bascally what I want is both to be redirected, SDTOut and SDTError if one should occur.
Any ideas?
Why not just take this:
process1.OutputDataReceived += (s, a) => myMethod(a);
process1.BeginOutputReadLine();
and add this: (Don't forget to add myErrorMethod!)
process1.ErrorDataReceived += (s, a) => myErrorMethod(a);
process1.BeginErrorReadLine();
Then take out this:
string error = process1.StandardError.ReadToEnd();
and instead, do this (if you want to wait for it to end):
process1.WaitForExit();
Basically, you cannot mix synchronous and asynchronous output reads. You have to either use Begin_______ReadLine() or read the stream objects, but not both.

Categories

Resources