I am working on creating web application and i am getting problem redirecting to another page,if I use redirect code in another method then it works fine but i want to use redirect code from my running thread and it is throwing me HttpExeption.Please can you take a look at this code and show right way to use redirect code in my runloop() method.Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Threading.Tasks;
public partial class _Default : System.Web.UI.Page
{
static TcpListener listener;
static TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public String receive = "kkkk";
public String text_to_send;
string Jsn;
string URI ;
string myParameters;
string URL1;
Thread backgroundThread2;
Thread backgroundThread;
int i, n = 0, k = 0, len = 0, len2 = 0;
public int readflag = 0, writeflag = 0, pre1 = 0, pre2 = 0, pre3 = 0, nopre = 0;
char[] ch = new char[100];
char[] ch1 = new char[100];
char[] ch2 = new char[100];
String test = null, s1, s2, s3;
String test1 = null;
string frame;
const int LIMIT = 5; //5 concurrent clients
protected void Page_Load(object sender, EventArgs e)
{
frame = Request.QueryString["frame"];
if (Request.QueryString["Frame"] != null)
Response.Write("From Page1 param1 value=" + Request.QueryString["frame"]);
}
public void Button1_Click(object sender, EventArgs e) //start server
{
listener = new TcpListener(IPAddress.Any, 8002);
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundThread = new Thread(new ThreadStart(RunLoop));
backgroundThread.Start();
// Task.Delay(50000);
//redirect1();
// Response.Redirect(URL1);
}
public void Button2_Click(object sender, EventArgs e) //Redirect server
{
Jsn = "25";
string URI = "Otherpage.aspx?";
string myParameters = "jasonop="+ Jsn;
string URL1 = URI + myParameters;
Response.Redirect(URL1);
// Response.Redirect("Otherpage.aspx?jasonop=25");
// System.Diagnostics.Process.Start("http://localhost:85/shaktijason/1.php?jasonop=25");
}
public class Person
{
public string Name { get; set; }
}
public void RunLoop() //receive
{
NetworkStream stream = client.GetStream();
Byte[] bytes = new Byte[256];
String data = null;
int i,k=1;
string str = "";
JavaScriptSerializer js = new JavaScriptSerializer();
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
byte[] bHex = Encoding.ASCII.GetBytes(data);
// TextBox1.Text = data;
string json = "[{Name:'01030008000105C8'}]";
Person[] persons = js.Deserialize<Person[]>(json);
string name = persons[0].Name.ToString();
// STW.WriteLine("01030008000105C8")
STW.WriteLine(name);
string result = decodedata(data);
str = result;
k++;
if (k == 4) { break; }
}
// string returnJson = "[{Freq:'" + str + "'}]";
Jsn = GetDeviceJSON(str);
URI = "Otherpage.aspx?";
myParameters = "jasonop="+Jsn;
URL1 = URI + myParameters;
Response.Redirect(URL1,false);
// Response.Redirect("Otherpage.aspx");
//string URI = "http://localhost:85/Shaktijason/1.php";
//string myParameters = "jasonop=jsn";
//using (WebClient wc = new WebClient())
//{
// wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// string HtmlResult = wc.UploadString(URI, myParameters);
// Response.Redirect(HtmlResult);
//}
//string JSON = Json;
//backgroundThread2.Start();
// backgroundThread.Abort();
//return js.Serialize(returnJson);
}
public string decodedata(string data)
{
ch1 = data.ToCharArray();
ch2 = data.ToCharArray();
int len1 = data.Count(char.IsLetter);
len2 = data.Count(char.IsNumber);
int add = len1 + len2;
while (ch1[k] != 'k')
{
ch2[k] = ch1[k];
k++;
}
string strng = new string(ch2, 0, k);
len = strng.Length;
string sub = data.Substring(k + 1);
len2 = sub.Length;
k = 0;
if (len == 1)
{
strng = "0" + strng.PadLeft(len, '0');
}
if (len2 == 1)
{
sub = "0" + sub.PadLeft(len2, '0');
}
char[] go = new char[20];
string final = strng + sub;
if (final.Equals("00b8"))
{
final = "0";
}
Decimal intAgain = long.Parse(final, System.Globalization.NumberStyles.HexNumber);
intAgain = intAgain / 100;
string final3 = intAgain.ToString();
// string final2 = new string(go);
return final3;
}
[WebMethod]
public static string GetValues(string values)
{
return values;
}
public string GetDeviceJSON(String str)
{
Device[] emps = new Device[] {
new Device()
{
Freq=str
}
//new employee()
//{
// id=102,
// name="dinesh",
// salary=100000
//}
};
return new JavaScriptSerializer().Serialize(emps);
}
}
You are trying to access the Reponse object from a background thread, where the response is already long gone.
You are not allowed to access the Response object, or any other object under HttpContext after the page has stopped rendering. Use web sockets or AJAX calls to create asynchronous requests and responses.
Related
I have this very simple code snippet in which a simple TCP listener is created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace TCPListenerTest
{
class Program
{
static void Main(string[] args)
{
IPAddress localAddr = IPAddress.Any;
TcpListener server = null;
bool done = false;
server = new TcpListener(localAddr, 5081);
server.Start();
while (!done)
{
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
//Connected!!
Console.WriteLine("Connected");
client.Close();
done = true;
}
Console.WriteLine("Done");
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}
When I run this code in a Console Application or in a Windows Form everything is fine, i.e. The listener accepts a connection from a client.
When I place this code inside a backgroundworker_DoWork, the client is unable to connect.
I wonder whether there is some issue when usingTCPListener from Backgroundworker.
EDIT: You were right, the TCP Listener works fine inside the background worker.
The code below works fine.
It sends a command (http:///config.cgi?F=8&A=) to an embedded board to start a file transfer.
The board acts as a client. It first request the total number of bytes and the number of packets it will receive. Successively the board sends a request for each packet until the full transfer is done.
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
namespace TCPListenerBackgroundWorkerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
String HostIP = "192.168.0.14";
String BoardIP = "192.168.0.144";
String pacchettozzoDest = "Italiano.bin";
void flasherase()
{
byte[] stream;
String cgireq = String.Format("http://{0}/config.cgi?F=8&A={1}", BoardIP, HostIP);
try
{
WebClient wClient = new WebClient();
stream = wClient.DownloadData(cgireq);
}
catch (Exception ex)
{
}
}
void updateProcess()
{
try
{
int updateProg;
int readBytes;
int n1 = 0;
int n2 = 0;
int PAYLOADSIZE = 1000;
int HEADERSIZE = 8;
UInt32 UpdateLength = 0;
int UpdatePackets = 0;
bool updateDone = false;
System.IO.FileStream messFile;
FileStream sr;
TcpListener server = null;
messFile = new FileStream(pacchettozzoDest, FileMode.Open, FileAccess.Read);
UpdateLength = (UInt32)messFile.Length;
UpdatePackets = (int)(UpdateLength / PAYLOADSIZE);
messFile.Close();
if ((UpdatePackets * PAYLOADSIZE) < UpdateLength)
UpdatePackets++;
server = new TcpListener(IPAddress.Any, 5081);
//Allocate Buffer fore reading data
byte[] TXbuffer = new byte[256];
byte[] RXbuffer = new byte[1024];
// Start listening for client requests.
server.Start();
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
//Connected!!
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
while (!updateDone)
{
readBytes = stream.Read(RXbuffer, 0, RXbuffer.Length);
if (readBytes >= HEADERSIZE)
{
if (RXbuffer[1] == 0xBE && RXbuffer[0] == 0xEA && RXbuffer[7] == 0xFC && RXbuffer[6] == 0xCF)
{
n1 = (RXbuffer[3] << 8) + RXbuffer[2];
n2 = (RXbuffer[5] << 8) + RXbuffer[4];
// First Packet
if (0 == n1 && 0 == n2)
{
byte[] bufferTX = new byte[HEADERSIZE];
bufferTX[1] = 0xBE; bufferTX[0] = 0xEA;
bufferTX[3] = (byte)((UpdatePackets & 0xFF00) >> 8);
bufferTX[2] = (byte)((UpdatePackets & 0xFF));
bufferTX[4] = (byte)((UpdateLength & 0x000000FF));
bufferTX[5] = (byte)((UpdateLength & 0x0000FF00) >> 8);
bufferTX[6] = (byte)((UpdateLength & 0x00FF0000) >> 16);
bufferTX[7] = (byte)((UpdateLength & 0xFF000000) >> 24);
stream.Write(bufferTX, 0, 8);
updateProg = 0;
}
else if (n1 > 0 && 0 == n2)
{
byte[] bufferTX = new byte[PAYLOADSIZE + HEADERSIZE];
bufferTX[0] = 0xEA;
bufferTX[1] = 0xBE;
bufferTX[2] = (byte)((n1 & 0xFF));
bufferTX[3] = (byte)((n1 & 0xFF00) >> 8);
updateProg = (n1 * 100) / UpdatePackets;
sr = File.OpenRead(pacchettozzoDest);
sr.Seek((n1 - 1) * PAYLOADSIZE, SeekOrigin.Begin);
int readB = 0;
int PaySize = 0;
for (int p = 0; p < PAYLOADSIZE; p++)
{
readB = sr.ReadByte();
if (readB != -1)
{
bufferTX[p + 6] = (byte)readB;
PaySize++;
}
else
{
break;
}
}
bufferTX[4] = (byte)((PaySize & 0xFF));
bufferTX[5] = (byte)((PaySize & 0xFF00) >> 8);
bufferTX[6 + PAYLOADSIZE] = 0xCF;
bufferTX[6 + PAYLOADSIZE + 1] = 0xFC;
sr.Close();
stream.Write(bufferTX, 0, (PAYLOADSIZE + HEADERSIZE));
updateProg = 0;
}
//End
else if ((0xFFFF == n1) && (0xFFFF == n2))
{
// Shutdown and end connection
client.Close();
updateProg = 100;
updateDone = true;
}
}
}
}
}
catch (Exception ex)
{
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPAddress localAddr = IPAddress.Any;
TcpListener server = null;
bool done = false;
flasherase();
updateProcess();
MessageBox.Show("Done");
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("BKGRW Completed");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
}
}
I have my two functions, the access attempt and the HMAC signing. It runs and returns an error(401) unauthorized, however in addition I feel my code is longer than it needs to be or redundant somehow, pointing that out would be very helpful to me, thanks in advance!
void AccessAttempt(){
var message = Epoch.ToString () + "GET" + "/v2/payment-methods";
const string WEBSERVICE_URL = "https://api.coinbase.com/v2/payment-methods";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("CB-ACCESS-SIGN", genHMAC(message));
webRequest.Headers.Add("CB-ACCESS-TIMESTAMP", Epoch.ToString());
webRequest.Headers.Add("CB-ACCESS-KEY", _apiKey);
webRequest.Headers.Add("CB-VERSION",_apiVersion);
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
}
Below is the HMAC signing function called within main function above:
private string genHMAC(string message)
{
byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret);
HMACSHA256 hmac = new HMACSHA256(APISecret_Bytes);
hmac.Initialize ();
byte [] MESSAGE_Bytes = System.Text.Encoding.UTF8.GetBytes(message);
var rawHmac = hmac.ComputeHash(MESSAGE_Bytes);
string rawHmacString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
rawHmacString += rawHmac[i];
}
string hexString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
hexString += rawHmac[i].ToString("X2");
}
return hexString;
}
This is a pretty old question, but in case you don't have an answer yet, it looks like there are a few things wrong with your request - here is some code that works for me
public class CoinbaseV2
{
private string APIKey;
private string Secret;
private const string URL_BASE = "https://api.coinbase.com";
private const string URL_BASE_VERSION = URL_BASE + "/v2/";
private const String GET = "GET";
private const String POST = "POST";
private const String PUT = "PUT";
private const String DELETE = "DELETE";
public CoinbaseV2(string inAPIKey, string inSecret)
{
APIKey = inAPIKey;
Secret = inSecret;
}
public string GetUser()
{
return JsonRequest(URL_BASE_VERSION + "user", GET);
}
public string GetUserAccounts()
{
return JsonRequest(URL_BASE_VERSION + "accounts", GET);
}
private string JsonRequest(string url, string method)
{
// take care of any spaces in params
url = Uri.EscapeUriString(url);
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = method;
webRequest.ContentType = "application/json";
string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.CurrentCulture);
string body = "";
string sigurl = url.Replace(URL_BASE,"");
string signature = GenerateSignature(timestamp,method,sigurl,body,Secret);
var whc = new WebHeaderCollection();
whc.Add("CB-ACCESS-SIGN", signature);
whc.Add("CB-ACCESS-TIMESTAMP", timestamp);
whc.Add("CB-ACCESS-KEY", APIKey);
whc.Add("CB-VERSION", "2017-08-07");
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
return returnData;
}
//https://github.com/bchavez/Coinbase
public static string GenerateSignature(string timestamp, string method, string url, string body, string appSecret)
{
return GetHMACInHex(appSecret, timestamp + method + url + body).ToLower();
}
internal static string GetHMACInHex(string key, string data)
{
var hmacKey = Encoding.UTF8.GetBytes(key);
var dataBytes = Encoding.UTF8.GetBytes(data);
using (var hmac = new HMACSHA256(hmacKey))
{
var sig = hmac.ComputeHash(dataBytes);
return ByteToHexString(sig);
}
}
//https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa/14333437#14333437
static string ByteToHexString(byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
int b;
for (int i = 0; i < bytes.Length; i++)
{
b = bytes[i] >> 4;
c[i * 2] = (char)(87 + b + (((b - 10) >> 31) & -39));
b = bytes[i] & 0xF;
c[i * 2 + 1] = (char)(87 + b + (((b - 10) >> 31) & -39));
}
return new string(c);
}
}
I am currently learning to program a chat room application that uses a server. So far everything works fine if I run the server and multiple instances of the application on a single machine. When I try to run the server on one machine and the actual chat application from another, I get an exception that reads "a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (Ipaddress)(port)"
Server side code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Text;
using System.Threading;
namespace ChatAppServer
{
class Program
{
public static Hashtable ClientList = new Hashtable();
const int PORT = 321;
string localIp;
static void Main(string[] args)
{
TcpListener sckServer = new TcpListener(PORT);
TcpClient sckClient = default(TcpClient);
int counter = 0;
sckServer.Start();
Console.WriteLine("Chat Server is now Running ....");
counter = 0;
//Parser myParser = new Parser();
while (true)
{
counter = counter + 1;
sckClient = sckServer.AcceptTcpClient();
string clientData = "";
byte[] recieveData = new byte[10025];
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
ClientList.Add(clientData, sckClient);
Broadcast(clientData + " joined the chat", clientData, false);
Console.WriteLine(clientData + " connected to the chat");
handleClient client = new handleClient();
client.ClientStart(sckClient, clientData, ClientList);
}
sckClient.Close();
sckServer.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void Broadcast(string msg, string userName, bool flag)
{
foreach (DictionaryEntry Item in ClientList)
{
TcpClient sckBroadcast;
sckBroadcast = (TcpClient)Item.Value;
NetworkStream broadcastStream = sckBroadcast.GetStream();
Byte[] broadcastData = null;
if (flag == true)
{
broadcastData = Encoding.ASCII.GetBytes(userName + ": " + msg);
}
else
{
broadcastData = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastData, 0, broadcastData.Length);
broadcastStream.Flush();
}
}
public class handleClient
{
TcpClient sckClient;
string clId;
Hashtable ClientList;
public void ClientStart(TcpClient inSckClient, string clientId, Hashtable clist) {
this.sckClient = inSckClient;
this.clId = clientId;
this.ClientList = clist;
Thread ctThread = new Thread(runChat);
ctThread.Start();
}
private void runChat() {
int requestCount = 0;
byte[] recieveData = new byte[10025];
string clientData = "";
string rCount = null;
while ((true))
{
try
{
requestCount += 1;
NetworkStream netStream = sckClient.GetStream();
netStream.Read(recieveData, 0, (int)sckClient.ReceiveBufferSize);
clientData = System.Text.Encoding.ASCII.GetString(recieveData);
clientData = clientData.Substring(0, clientData.IndexOf("$"));
Console.WriteLine(clId + " : " + clientData);
rCount = Convert.ToString(requestCount);
Program.Broadcast(clientData, clId, true);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
}
}
Chat room application code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//Need for the application
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ChatApp
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient sckClient = new System.Net.Sockets.TcpClient();
NetworkStream svrStream = default(NetworkStream);
string recieveData = null;
public Form1()
{
InitializeComponent();
btnSend.Enabled = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
recieveData = "Connected to Server";
msg();
int serverPort = Convert.ToInt32(txtServerPort.Text);
sckClient.Connect(txtServerIp.Text, serverPort);
svrStream = sckClient.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtUserName.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
Thread ctThread = new Thread(MessageCallBack);
btnSend.Enabled = true;
btnConnect.Enabled = false;
txtUserName.Enabled = false;
txtServerIp.Enabled = false;
txtServerPort.Enabled = false;
ctThread.Start();
}
private void MessageCallBack()
{
while(true)
{
svrStream = sckClient.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = sckClient.ReceiveBufferSize;
svrStream.Read(inStream, 0, buffSize);
string returnData = System.Text.Encoding.ASCII.GetString(inStream);
recieveData = "" + returnData;
msg();
}
}
//function to display data strings
private void msg()
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(msg));
}
else
{
lstMessage.Items.Add(recieveData);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtMessage.Text + "$");
svrStream.Write(outStream, 0, outStream.Length);
svrStream.Flush();
txtMessage.Text = "";
}
I have two troubles with your code :
Do not use .ReceiveBufferSize value because it's a different value of your byte array length. And you can have an index out of range exception.
You have a problem of concurrency in the server side. More than 1 thread try to access to the ClientList and this collection is not thread-safe.
To resolve this, you can use the lock keyword
private static object _lock = new object();
//...
lock (_lock)
{
ClientList.Add(clientData, sckClient);
}
lock (_lock)
{
Broadcast(clientData + " joined the chat", clientData, false);
}
//...
lock (_lock)
{
Program.Broadcast(clientData, clId, true);
}
As you're a beginner, i would give you some tips.
Try to use the asynchronous network functions (better than raw threads), an example there.
There is a lot of tutorials about safety with severals connections in C# (with some thing else, better, than the lock keyword).
So i recently decided to again redo the infrastructure of my Jarvis AI. Now i'm using a mix of the code (Google and Microsoft). The Google part of the code will not trigger for some reason and display any words or text when spoken into microphone.
public const int DEFAULT_BIT_RATE = 8000;
public const string DEFAULT_LANGUAGE = "en-US";
static string client = "Jarvis";
public class SpeechInputResult
{
static public string ID;
public int status;
public class Hypothesis
{
public string utterance;
public double confidence = -1.0d;//-1 = No Value
public override string ToString()
{
return "'" +utterance + "'" + ((confidence == -1) ? "" : "#" + confidence);
}
public List<Hypothesis> hypotheses = new List<Hypothesis>();
public Hypothesis getBestHypothesis()
{
if (hypotheses.Count() <=0)
return null;
Hypothesis H = hypotheses[0];
foreach (Hypothesis h in hypotheses)
{
if (h.confidence>=H.confidence)
{
H = h;
}
return H;
}
return null;
}
public string json_men = "";
public void FromJSON(String JSON)
{
json_men = JSON;
JSON = JSON.Replace("\n","").Trim();
Match M;
//status
M = new Regex("\\\"status\\\"\\:([0-9]*),", RegexOptions.IgnoreCase).Match(JSON);
//ID
M = new Regex ("\\\"id\\\"\\:\\\"([^\\\"]*)\\\",", RegexOptions.IgnoreCase).Match(JSON);
ID = M.Groups[1].Value;
//Hypotheses
int l1 = JSON.IndexOf("hypotheses");
l1 = JSON.IndexOf("[",l1);
int r1 = JSON.LastIndexOf("]");
string JSON2 = JSON.Substring(l1, r1-l1+1);
MatchCollection m2 = new Regex("{([^\\}]*)}", RegexOptions.IgnoreCase).Matches(JSON2);
foreach (Match g in m2)
{
string s = g.Value;
SpeechInputResult.Hypothesis h = new SpeechInputResult.Hypothesis();
M = new Regex("\\\"utterance\\\"\\:\\\"([^\\\"]*)\\\"", RegexOptions.IgnoreCase).Match(s);
h.utterance = M.Groups[1].Value;
M = new Regex("\\\"confidence\\\"\\:([0-9\\.]*)", RegexOptions.IgnoreCase).Match(s);
string confidence = M.Groups[1].Value;
confidence = confidence.Replace(".", ",");
if (confidence != "")
{
h.confidence = float.Parse(confidence);
}
hypotheses.Add(h);
}
}
}
public static SpeechInputResult ProcessFlacFile(string FlacFileName, int BIT_RATE = DEFAULT_BIT_RATE, string language = DEFAULT_LANGUAGE, uint maxresults = 1)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/speech-api/v1/recognize?xjerr=1" + "&client=" + client + "&lang=" + language + "&maxresults=" + maxresults + "&pfilter=0");
FileStream fStream = new FileStream(FlacFileName, FileMode.Open, FileAccess.Read);
request.Proxy = null;
request.Timeout = 60000;
request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "audio/x-flac; rate=8000";
//bitrate must = .flac file
request.UserAgent = client;
FileInfo fInfo = new FileInfo(FlacFileName);
long numbytes = fInfo.Length;
byte[] data = null;
using (FileStream fstream = new FileStream(FlacFileName, FileMode.Open, FileAccess.Read))
data = new byte[fstream.Length];
fStream.Read(data, 0, Convert.ToInt32(fStream.Length));
fStream.Close();
using (Stream wrStream = request.GetRequestStream())
{
wrStream.Write(data, 0, data.Length);
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dynamic resp = response.GetResponseStream();
if (resp != null)
{
StreamReader sr = new StreamReader(resp);
MessageBox.Show(sr.ReadToEnd());
//resp.Close();
//resp.Dispose();
}
}
catch (System.Exception ee)
{
MessageBox.Show("hi"+ee);
}
return null;
}
}
}
The code here is all from this website.
After getting it to no errors it still doesn't return or do anything, please help!
Parsing JSON with regular expressions will usually cause you problems. Consider using a library like JSON.NET to parse the string into an object instead.
I'm new in C# and I am practicing with Socket programming.
First I created a server for client connect to it.
Server:
class Program {
static void Main(string[] args) {
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 1900);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
Console.WriteLine("Waiting for a client...");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
while (true) {
data = new byte[1024];
recv = newsock.ReceiveFrom(data, ref Remote);
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
newsock.SendTo(data, recv, SocketFlags.None, Remote);
}
}
}
Client:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace serverUDPWF {
public partial class ServerForm : Form {
byte[] data = new byte[30];
string input = "";
string stringData = "";
IPEndPoint iep,sender;
Socket server;
string welcome = "";
int recv;
EndPoint tmpRemote;
public ServerForm() {
InitializeComponent();
startServer();
}
public void startServer() {
iep = new IPEndPoint(
IPAddress.Parse("127.0.0.1"), 1900);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, iep);
sender = new IPEndPoint(IPAddress.Any, 0);
tmpRemote = (EndPoint)sender;
data = new byte[30];
recv = server.ReceiveFrom(data, ref tmpRemote);
Console.WriteLine();
listBox1.Items.Add("Message received from {0}:" + tmpRemote.ToString());
listBox1.Items.Add(Encoding.ASCII.GetString(data, 0, recv));
}
private void sendMessageToserver(object sender, EventArgs e) {
if (textBox2.Text == "") {
MessageBox.Show("Please Enter Your Name");
}
else {
int i = 30;
input = textBox2.Text + ": " + textBox1.Text;
if (input == "exit") {
this.Close();
}
server.SendTo(Encoding.ASCII.GetBytes(input), tmpRemote);
textBox1.Text = "";
data = new byte[i];
try {
recv = server.ReceiveFrom(data, ref tmpRemote);
stringData = Encoding.ASCII.GetString(data, 0, recv);
listBox1.Items.Add(stringData);
}
catch (SocketException) {
listBox1.Items.Add("WARNING: data lost, retry message.");
i += 10;
}
}
}
}
}
My problem is how to make client not need to enter the server ip address like 127.0.0.1. My Second problem is I open 2 client in the same time, but client A sends a message to server but client B doesn't receive a message from client A (I want send a broadcast type message)
How can I do that?
Multicast udp communication.. i just try if anything wrong feel free to share
Client:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Threading;
namespace Myclient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
Socketsending socketsending;
string multicastIP = string.Empty;
int multicastPort = 0;
int clientPort = 0;
string clientSysname = string.Empty;
string Nodeid = string.Empty;
string clientIP = string.Empty;
string recievedText = string.Empty;
string sendingText = string.Empty;
IPAddress ipAddress;
IPEndPoint ipEndpoint;
UdpClient udpClient;
string[] splitRecievedText;
byte[] byteRecieve;
private void Form1_Load(object sender, EventArgs e)
{
Random _random = new Random();
multicastIP = "224.5.6.7";
multicastPort = 5000;
Nodeid = "node" + _random.Next(1000, 9999);
clientPort = _random.Next(1000, 9999);
clientSysname = Dns.GetHostName();
ipAddress = Dns.GetHostEntry(clientSysname).AddressList.FirstOrDefault
(addr => addr.AddressFamily.Equals(AddressFamily.InterNetwork));
ipEndpoint = new IPEndPoint(ipAddress, clientPort);
clientIP = ipAddress.ToString();
label1.Text = "Node id: " + Nodeid;
label2.Text = "Host Name: " + clientSysname;
Thread threadMain = new Thread(connect);
threadMain.Start();
threadMain = new Thread(receive);
threadMain.Start();
}
void connect()
{
socketsending = new Socketsending();
sendingText = "connect#" + clientSysname + "#" + clientIP + "#" + clientPort + "#" + Nodeid + "#";
socketsending.send(multicastIP, multicastPort, sendingText);
}
void receive()
{
udpClient = new UdpClient(clientPort);
while (true)
{
IPEndPoint _ipendpoint = null;
byteRecieve = udpClient.Receive(ref _ipendpoint);
recievedText = Encoding.ASCII.GetString(byteRecieve);
splitRecievedText = recievedText.Split('#');
if (splitRecievedText[0] == "stop")
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
sendingText = "message#" + Nodeid + '$' + textBox1.Text + '$';
socketsending.send(multicastIP, multicastPort, sendingText);
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Collections;
namespace Myserver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
string multicastip = string.Empty;
string serversystemname = string.Empty;
string receiveddata = string.Empty;
string nodeinfo = string.Empty;
string clientHostName = string.Empty;
string clientIP = string.Empty;
string Nodeid = string.Empty;
int multicastport = 0;
int clientport = 0;
DataTable datatable;
DataTable dataTableAddRemove;
string[] splitReceived;
string[] splitnodeinfo;
Socket socket;
IPAddress ipaddress;
IPEndPoint ipendpoint;
byte[] bytereceive;
Dictionary<string, string> dictionarytable;
public delegate void updategrid();
private void Form1_Load(object sender, EventArgs e)
{
multicastip = "224.5.6.7";
multicastport = 5000;
serversystemname = Dns.GetHostName();
datatable = new DataTable();
datatable.Columns.Add("HostName");
datatable.Columns.Add("Nodeid");
datatable.Columns.Add("ipaddress");
datatable.Columns.Add("portnumber");
DGV.DataSource = datatable;
Thread threadreceive = new Thread(receiver);
threadreceive.Start();
}
void receiver()
{
dictionarytable = new Dictionary<string, string>();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
ipendpoint = new IPEndPoint(IPAddress.Any, multicastport);
socket.Bind(ipendpoint);
ipaddress = IPAddress.Parse(multicastip);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipaddress, IPAddress.Any));
while (true)
{
bytereceive = new byte[4200];
socket.Receive(bytereceive);
receiveddata = Encoding.ASCII.GetString(bytereceive, 0, bytereceive.Length);
splitReceived = receiveddata.Split('#');
if (splitReceived[0].ToString() == "connect")
{
nodeinfo = splitReceived[1].ToString();
connect();
}
else if (splitReceived[0].ToString() == "Disconnect")
{
nodeinfo = splitReceived[1].ToString();
Thread threadDisconnect = new Thread(disconnect);
threadDisconnect.Start();
}
else if (splitReceived[0].ToString() == "message")
{
string[] str = splitReceived[1].Split('$');
listBox1.Items.Add(str[0] + " -> " + str[1]);
}
}
}
void connect()
{
SocketSending socketsending = new SocketSending();
int count = 0;
splitnodeinfo = nodeinfo.Split('#');
clientHostName = splitnodeinfo[0].ToString();
clientIP = splitnodeinfo[1].ToString();
clientport = Convert.ToInt32(splitnodeinfo[2].ToString());
Nodeid = splitnodeinfo[3].ToString();
if (!dictionarytable.ContainsKey(Nodeid))
{
count++;
dictionarytable.Add(Nodeid, clientIP + "#" + clientport + "#" + clientHostName);
dataTableAddRemove = (DataTable)DGV.DataSource;
DataRow dr = dataTableAddRemove.NewRow();
dr["Nodeid"] = Nodeid;
dr["HostName"] = clientHostName;
dr["IPAddress"] = clientIP;
dr["portNumber"] = clientport;
dataTableAddRemove.Rows.Add(dr);
datatable = dataTableAddRemove;
updatenodegrid();
}
}
void disconnect()
{
SocketSending socketsending = new SocketSending();
string removeClient = string.Empty;
splitnodeinfo = nodeinfo.Split('#');
clientHostName = splitnodeinfo[0].ToString();
Nodeid = splitnodeinfo[1].ToString();
dataTableAddRemove = (DataTable)DGV.DataSource;
DataRow[] arrayDataRow = dataTableAddRemove.Select();
for (int i = 0; i < arrayDataRow.Length; i++)
{
string matchGridHostName = arrayDataRow[i]["HostName"].ToString();
if (clientHostName == matchGridHostName)
{
Thread.Sleep(100);
removeClient = clientHostName;
arrayDataRow[i].Delete();
break;
}
}
if (dictionarytable.ContainsKey(removeClient))
{
dictionarytable.Remove(removeClient);
}
}
void updatenodegrid()
{
if (this.DGV.InvokeRequired)
this.DGV.Invoke(new updategrid(updatenodegrid));
else
DGV.DataSource = datatable;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
dictionarytable.Clear();
}
}
}