Send a number via TCP IP in C# - tcp

I want to send a number in Integer via TCP IP. I save a data in Send_data as a Integer's number.
I can't change it to a string or char[] in order to send it. I only receive a space in Client when I run this code.
This is my code:
NetworkStream clientStream = MyClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = BitConverter.GetBytes(Send_data[0]);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();

tcp client declaration and connection:
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("IP_address"), port);
TcpClient client = new TcpClient();
client.Connect(endPoint);
NetworkStream declaration:
NetworkStream networkStream = client.GetStream();
BinaryFormatter for serilazation
BinaryFormatter formatter = new BinaryFormatter();
//int goes here
formatter.Serialize(networkStream , Send_data);

Related

Bing Speech API giving error with JAVA code

I am trying to use Bind Speech Rest API from Java service but every time I am getting 408 response code.
java.io.IOException: Server returned HTTP response code: 408 for URL: https://speech.platform.bing.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US
I have tried calling REST API using diffrent methods but all the time, error is 408 Request time out.
Whereas I created a .net sample with similar code of calling Speech REST API, it is working.
Is there any way to diagnose what I am missing in my Java code ?
Here is my JAVA code
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1024; // 1024*1024 = 1MB. 212144 is a quarter MB.
FileInputStream fileInputStream = null;
fileInputStream = new FileInputStream(new File("D://hello.wav"));
URL url = new URL("https://speech.platform.bing.com/speech/recognition/conversation/cognitiveservices/v1?language=en-US");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
conn.setRequestProperty("Transfer-Encoding", "chunked");
conn.setRequestProperty("Accept","application/json;text/xml");
conn.setRequestProperty("Host","speech.platform.bing.com");
//header
conn.setRequestProperty("content-length", String.valueOf(fileInputStream.available()));
conn.setRequestProperty("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000;");
conn.setRequestProperty("Authorization", "Bearer "+ token );
conn.setReadTimeout(22222230);
conn.setDoOutput(true);
conn.connect();
dos = new DataOutputStream(conn.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
try {
dos.write(buffer, 0, bufferSize);
} catch (OutOfMemoryError oome) {
oome.printStackTrace();
fileInputStream.close();
throw new Exception("Out Of Memory!");
}
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
fileInputStream.close();
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
The Bing Speech API wants chunked transfer of the audio data. For the HttpURLConnection class, though, setting the Transfer-Encoding header does not magically cause the transfer type to switch -- you need to set the streaming mode explicitly through the setChunkedStreamingMode or one of its variants. You'll also want to omit the Content-Length header.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//method
conn.setRequestMethod("POST");
conn.setChunkedStreamingMode(0);
//header
conn.setRequestProperty("Accept","application/json;text/xml");
conn.setRequestProperty("Content-Type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000;");
conn.setRequestProperty("Authorization", "Bearer "+ token );

remote server returned an error (401) unauthorized

Written code to get the notification on android device.
In this added the device id and registration id and application id of that android application but i run this page getting this error....
The remote server returned an error: (401) Unauthorized.
private void AndroidPush()
{
string regId = "[the regid]";
// applicationID means google Api key
var applicationID = "[the key]";
//ProjectID (from API Console- google code)
var SENDER_ID = "[the id]";
var value = Text1.Text; //message text box
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
tRequest.UseDefaultCredentials = true;
tRequest.PreAuthenticate = true;
tRequest.Credentials = CredentialCache.DefaultCredentials;
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + regId + "";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd(); //Get response from GCM server.
Label3.Text = sResponseFromServer; //Assigning GCM response to Label text
tReader.Close();
dataStream.Close();
tResponse.Close();
}
You can't connect to remote server if you don't enter Username and Password
Check This Answer might be helpful.

download file from remote server asp.net

I am trying to download file from a file hosting server, using my username and password through my own website.
I already achieve the possibility to connect and download the file, with the code attached below.
my problem is this code doesn't support resume of download and my download manager isn't able to open more then one connection to the remote site ,so the speed is very low(the remote site Of course is supporting those features)
my main goal is to let me download this file with full speed and with the ability to resume the download in any Second.
this is the code
//the login method
ASCIIEncoding encoding = new ASCIIEncoding();
string url = "RemoteServerLoginPage/loginPage";
string postVariables = "id=myIdToTheServer";
postVariables += "&password=MyPasswordToTheServer";
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
webRequest.CookieContainer = cookies;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postVariables.Length;
byte[] data = encoding.GetBytes(postVariables);
Stream newStream = webRequest.GetRequestStream();
// Send the request
newStream.Write(data, 0, data.Length);
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
//after login get the file with thr right cookies
string url2 = "UrlOfRemoteServerFileAdress/filename.rar";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url2);
req.CookieContainer = cookies;
HttpWebResponse resp2 = (HttpWebResponse)req.GetResponse();
////Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=myfile.rar");
Response.AppendHeader("Content-Length:", "bytes");
Response.AppendHeader("Connection:", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AppendHeader("AcceptRanges", resp2.ContentLength.ToString());
const int BufferLength = 4 * 1024 * 1024;
byte[] byteBuffer = new byte[BufferLength];
Stream rs = req.GetResponse().GetResponseStream();
int len = 0;
while ((len = rs.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (len < BufferLength)
{
Response.BinaryWrite(byteBuffer.Take(len).ToArray());
}
else
{
Response.BinaryWrite(byteBuffer);
}
Response.Flush();
}

Check if Email Address Belongs to Yahoo?

private byte[] BytesFromString(string str)
{
return Encoding.ASCII.GetBytes(str);
}
private int GetResponseCode(string ResponseString)
{
return int.Parse(ResponseString.Substring(0, 3));
}
protected void Button1_Click(object sender, EventArgs e)
{
TcpClient tClient = new TcpClient("plus.smtp.mail.yahoo.com", 465);
string CRLF = "\r\n";
byte[] dataBuffer;
string ResponseString;
NetworkStream netStream = tClient.GetStream();
StreamReader reader = new StreamReader(netStream);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("HELO " + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("MAIL FROM:<myemail#yahoo.com>" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
dataBuffer = BytesFromString("RCPT TO:<" + TextBox1.Text.Trim() + ">" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
ResponseString = reader.ReadLine();
if (GetResponseCode(ResponseString) == 550)
{
Response.Write("Mai Address Does not Exist !");
}
dataBuffer = BytesFromString("QUITE" + CRLF);
netStream.Write(dataBuffer, 0, dataBuffer.Length);
tClient.Close();
}
Hi, this code does not work with smtp yahoo server but code work with gmail smtp server TcpClient tClient = new TcpClient("gmail-smtp-in.l.google.com", 25)
error:An established connection was aborted by the software in your host machine in line Response String = reader.ReadLine();
and change port server to 25 not happen!
Whether smtp server and port server is valid?
Is there a way to make sure of is email valid?
someone could help me?
Some Server machine used to algorithm for responsing to fetch data from it's particular server than that machine can't responding.....
but as you say gmail provide data therefore that machine can't use any restriction for responding data......

Need example for testing an asp.net web handler deployed on a server

I have modified asp.net web handler and deployed it on a server.
The handler works greate on my local machine using a static XML file but
is giving IIS 500 errors when deployed.
Is there and example which I could use to modify my code to run against a
live data feed ?
This is what I have used with the static file :
WebRequest req = null;
WebResponse rsp = null;
try
{
string uri = "https://mytestSite.com/Test_Handler.ashx";
req = WebRequest.Create(uri);
req.Method = "POST"; // Post method
req.ContentType = "text/xml"; // content type
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the XML text into the stream
//StreamReader reader = new StreamReader(Server.MapPath("~/20121129-0121-1.xml"));
-- Would this line capture the stream ????????
StreamReader reader = new StreamReader(req.GetRequestStream());
string ret = reader.ReadToEnd();
reader.Close();
writer.WriteLine(ret);
writer.Close();
// Send the data to the webserver
rsp = req.GetResponse(); //Calls the handler code
StreamReader sr = new StreamReader(rsp.GetResponseStream());
string responseString = sr.ReadToEnd();
sr.Close();

Resources