C# Client to server. Get server response? - c#

I am having trouble reading the response of the server after it has been read before. I can get the response of the server the first time it has been read but when I send something else back to the server the response will be null and I get a crash on the response = sr.ReadToEnd();.
What should happen with the two args is it updates the location with the second arg. Then it sends to the server and then the server responds with Ok. In following requests the new location is used instead of the first one.
The error message complains abouut line 102, which is:
response = sr.ReadToEnd();
This is the first writing of the args to the server and the response being given.
// these are the args being sent to the server
sw.WriteLine(args[0]);
// the flush sends this to the server which the response is then read
sw.Flush();
try
{
response = sr.ReadToEnd();
//[some if statement...]
else if (args.Length == 2)
{
//response = sr.ReadLine();
if (args[1] != response)
{
// this is what should be put in 'sw.write()' for the updated database entry
// <name><space><location><CR><LF>
// cssbct + " " + "is in fenner", so "cssbct location has changed"
// args[0] + " " + response
// response is now what the arg is
response = args[1];
// write the new response so that it will be sent to the server
sw.WriteLine(args[0] + " " + response);
// send it to the server
sw.Flush();
// write out the args and that the location has changed
Console.WriteLine(args[0] + " " + " location changed to be" + " " + response);
// just testing what the response should be
Console.WriteLine(args[0] + " " + response);
// read the response from the server
response = sr.ReadToEnd();
// if it equals "OK" do this
if (response == "OK")
{
// drops connection to the server
// probably not what is needed but look at later date
Console.WriteLine(response);
Console.WriteLine("Client connection closed");
client.Close();
}
}
}
sw.Flush();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Is what I am doing the correct way to receive the second response by the server?
I dont find a way using the streamReader/Writer to get the second response of the server.
EDIT: The connections
string response = "";
TcpClient client = new TcpClient();
client.Connect("whois.net.dcs.hull.ac.uk", 43);
// client.Connect("whois.networksolutions.com", 43);
Stream stream = client.GetStream();
StreamWriter sw = new StreamWriter(client.GetStream(), Encoding.ASCII);
StreamReader sr = new StreamReader(client.GetStream(), Encoding.ASCII);
Spec of the Client and server response
A request from Client to server Using 1 Arg: name CR LF
A request from client to server Using 2 Args to update the DB:
name space location CRLF
Server responses (don't have access to the server code, it is just said it will just do such things)
A response from server looks like:
[drops connection]
If no entries are found
"ERROR: no entries found
[drops connection]
If the server updates the database wit the new location:
OK
[drops connection]
An idea: Could the reason for the response being null be that it has reached the end of the stream?

Related

.NET public http listener running alongside with Apache

I have a simple part of the code that creates a http listener for a specific url. Everything works perfectly, untill I turn on Xampp - Apache Web Server. At that moment, whenever I try to run the listener, I get Address already in use exeption.
I did some research and found a possible cause: I guess it won't work because Apache is listening to http port(idk if it is a proper term, it is what I got from running lsof-i:http command.), therefore my app cannot start the listener on http. But it is weird, since I have full url specified, so I suppose if request matches the url, Apache should stay away from it... Maybe I am wrong...
Does anyone know a solution how I could run Apache and my http listener at the same time?
Also I am running Debian 10 if it helps. Thanks in advance!
HttpListener listener2 = new HttpListener();
listener2.Prefixes.Clear();
listener2.Prefixes.Add("http://xxxx.xxxx.eu/");
listener2.Start();
LogWriteLine("http listener started listening to: " +listener2.Prefixes);
try
{
while (true)
{
HttpListenerContext context = listener2.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (!request.HasEntityBody)
{
LogWriteLine("No client data was sent with the request.");
Thread.Sleep(300);
}
if (request.ContentType != null)
{
LogWriteLine("Client data content type " + request.ContentType);
}
LogWriteLine("Client data content length " + request.ContentLength64);
LogWriteLine("Start of client data:");
string s = reader.ReadToEnd();
var bytes = default(byte[]);
using (var reader1 = new StreamReader(request.InputStream,
request.ContentEncoding))
{
text = reader1.ReadToEnd();
using (var memstream = new MemoryStream())
{
memstream.Position = 0;
reader1.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
memstream.Position = 0;
Console.WriteLine("memstream length: " + memstream.Length);
}
Console.WriteLine("bytes:" + bytes.Length); //output: bytes: 0
}
LogWriteLine("End of client data:");
response.StatusCode = (int)HttpStatusCode.OK;
response.Close();
body.Close();
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

Cannot read data from HttpListener .NET

I am stuck with reading data from HttpListener. Data arrives, I verify it with request.ContentLength64 that is usually over 8000 and it increases as the server generates more and more data.
The server sends data as HTTP post and the content type is text/plain.
When I try to check whether streamreader got some data via its length attribute I get 0.
The code is a little bit messy as I was trying different ways to make it work but unfortunatelly I had no luck.
Does anyone got an idea what I'm doing wrong?
Thanks!
HttpListener listener2 = new HttpListener();
listener2.Prefixes.Clear();
listener2.Prefixes.Add("http://+:4200/");
listener2.Prefixes.Add("http://XXX.XXX.eu/");
listener2.Start();
LogWriteLine("http listener started listening to: " +listener2.Prefixes);
try
{
while (true)//change to match end check
{
LogWriteLine("http listener waiting");
HttpListenerContext context = listener2.GetContext();
LogWriteLine("http request arrived");
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (!request.HasEntityBody)
{
LogWriteLine("No client data was sent with the request.");
Thread.Sleep(300);
//return;
}
if (request.ContentType != null)
{
LogWriteLine("Client data content type " + request.ContentType);
}
LogWriteLine("Client data content length " + request.ContentLength64); //Works fine
LogWriteLine("Start of client data:");
// Convert the data to a string and display it on the console.
Console.WriteLine(body.CanSeek);
string s = reader.ReadToEnd();
var ahoj = new StreamReader(context.Request.InputStream).ReadToEnd();
Console.WriteLine("ahoj length " + ahoj.Length); //0
Console.WriteLine(s); //nothing
string text;
var bytes = default(byte[]);
using (var reader1 = new StreamReader(request.InputStream,
request.ContentEncoding))
{
text = reader1.ReadToEnd();
Console.WriteLine(text + text.Length); //output: 0
using (var memstream = new MemoryStream())
{
reader1.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
Console.WriteLine("bytes:" + bytes.Length); //output: bytes: 0
}
LogWriteLine("End of client data:");
//write to console file
sw.Write(s);
body.Close();
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

Textfree Login Authentication Failing

I am trying to create a C# application that logs in to a Pinger Textfree account and can send SMS messages from it. The web version of this service is flash-based so I have been using Fiddler and Wireshark to monitor the HTTP requests that it uses. I have written some code that I think should log in but I get a "Bad Credentials" response from the server, however, I do know that the username and password I am using are accurate. I am also pretty sure that they do not append anything extra to either as I would have seen this in Fiddler.
static void Main(string[] args)
{
// Connect as client to port 443
string server = "api.pinger.com";
TcpClient client = new TcpClient(server, 443);
// Create a secure stream
using (SslStream sslStream = new SslStream(client.GetStream(), false,
new RemoteCertificateValidationCallback(ValidateServerCertificate), null))
{
sslStream.AuthenticateAsClient(server);
byte[] data = System.Text.Encoding.ASCII.GetBytes("POST https://api.pinger.com/1.0/web/login HTTP/1.1\r\n" +
"Host: api.pinger.com\r\n" +
"Connection: keep-alive\r\n" +
"Origin: http://pinger.com\r\n" +
"X-Rest-Method: POST\r\n" +
"Authorization: OAuth realm=\"https://api.pinger.com\", oauth_consumer_key=\"textfree-in-flash-web-free\", oauth_signature_method=\"HMAC-SHA1\", oauth_signature=\"HNN8gdLdskKnrtK2jbyN68b9JWQ%3D\", oauth_timestamp=\"1406102776\", oauth_nonce=\"635733471764340000\"\r\n" +
"Content-Type: application/json\r\n" +
"Accept: */*\r\n" +
"Referer: http://pinger.com/tfw/textFree_web.swf\r\n" +
"Accept-Encoding: gzip,deflate,sdch\r\n" +
"Accept-Language: en-US,en;q=0.8\r\n\r\n" +
//json info
"{\"password\":\"testing\",\"username\":\"myquestion\",\"clientId\":\"textfree-in-flash-web-free-1406143265-10D066F9-8126-CD00-4C3D-64AB7BA4FF52\"}\r\n"
);
sslStream.Write(data);
data = new byte[client.ReceiveBufferSize];
int bytesRead = -1;
do
{
bytesRead = sslStream.Read(data, 0, data.Length);
using (MemoryStream ms = new MemoryStream(data, 0, bytesRead))
using (StreamReader rd = new StreamReader(ms))
{
string returnData = rd.ReadToEnd();
Console.WriteLine(returnData);
}
} while (bytesRead != 0);
Console.ReadKey();
}
}
PS I created the account with these credentials (User: myquestion, Pass: testing) just for this question so they are correct and it should be working.
I am using the headers and formatting that the requests I recorded with Fiddler used.
My guesses as to why this attempt has failed is that I am either not posting the json correctly or the authorization header is incorrect or its the "clientId" key in the json. I have done a lot of trial and error as well as research and any help would be appreciated.

toast notification in windows phone 8 - stream error

I have download toast notification sample code from microsoft site but the code is not executed properly -- giving an error in httpwebresponse --
protected void ButtonSendToast_Click(object sender, EventArgs e)
{
try
{
// Get the Uri that the Microsoft Push Notification Service returns to the Push Client when creating a notification channel.
// Normally, a web service would listen for Uri's coming from the web client and maintain a list of Uri's to send
// notifications out to.
string subscriptionUri = TextBoxUri.Text.ToString();
HttpWebRequest sendNotificationRequest = (HttpWebRequest)WebRequest.Create(subscriptionUri);
// We will create a HTTPWebRequest that posts the toast notification to the Microsoft Push Notification Service.
// HTTP POST is the only allowed method to send the notification.
sendNotificationRequest.Method = "POST";
// The optional custom header X-MessageID uniquely identifies a notification message.
// If it is present, the // same value is returned in the notification response. It must be a string that contains a UUID.
// sendNotificationRequest.Headers.Add("X-MessageID", "<UUID>");
// Create the toast message.
string toastMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>" + TextBoxTitle.Text.ToString() + "</wp:Text1>" +
"<wp:Text2>" + TextBoxSubTitle.Text.ToString() + "</wp:Text2>" +
"<wp:Param>/Page2.xaml?NavigatedFrom=Toast Notification</wp:Param>" +
"</wp:Toast> " +
"</wp:Notification>";
// Sets the notification payload to send.
byte[] notificationMessage = Encoding.Default.GetBytes(toastMessage);
// Sets the web request content length.
sendNotificationRequest.ContentLength = notificationMessage.Length;
sendNotificationRequest.ContentType = "text/xml";
sendNotificationRequest.Headers.Add("X-WindowsPhone-Target", "toast");
sendNotificationRequest.Headers.Add("X-NotificationClass", "2");
using (Stream requestStream = sendNotificationRequest.GetRequestStream())
{
requestStream.Write(notificationMessage, 0, notificationMessage.Length);
}
// Send the notification and get the response.
HttpWebResponse response = (HttpWebResponse)sendNotificationRequest.GetResponse(); // Exception in this line
string notificationStatus = response.Headers["X-NotificationStatus"];
string notificationChannelStatus = response.Headers["X-SubscriptionStatus"];
string deviceConnectionStatus = response.Headers["X-DeviceConnectionStatus"];
// Display the response from the Microsoft Push Notification Service.
// Normally, error handling code would be here. In the real world, because data connections are not always available,
// notifications may need to be throttled back if the device cannot be reached.
TextBoxResponse.Text = notificationStatus + " | " + deviceConnectionStatus + " | " + notificationChannelStatus;
}
catch (Exception ex)
{
TextBoxResponse.Text = "Exception caught sending update: " + ex.ToString();
}
}
}
I tried running this code in vs 2010 and vs 2013 express but still got the same error

Service HTTP Post is receiving "Existing Connection Was Forcibly Closed"

I have a windows service that I am trying to get running on a server. It just posts data to a php page and has further logic based on the response back. This works 100% on my machine and 100% on the server WHEN Anonymous Authenication is turned on for the website(IIS).
What I want to accomplish is to run the site with Windows Authenication turned ON and have my service still work... except when I try this I receive a nice EventLog entry.
"System.IO.IOException: Unable to read data from the transport
connection: An existing connection was forcibly closed by the remote
host"
I am running the service under an account that has all required permissions. So I understand that "CredentialCache.DefaultCredentials" should use this account for authentication( I am not receiving a 401 error ,but not ruling it out )
Below is my HttpPost code, I have set quite a few options from other posts trying to find a solution.
string postData = xml;
//--------------
HttpRequestCachePolicy policy = new HttpRequestCachePolicy MontgP02(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest.DefaultCachePolicy = policy;
byte[] buffer = Encoding.UTF8.GetBytes(postData);
//Initialisation
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
//Credentials
WebReq.UseDefaultCredentials = true;
WebReq.PreAuthenticate = true;
WebReq.Credentials = CredentialCache.DefaultCredentials;
//Request Settings
WebReq.ProtocolVersion = HttpVersion.Version11;
//WebReq.ServicePoint.ConnectionLimit = 1;
WebReq.Method = "POST";
WebReq.ContentType = "application/x-www-form-urlencoded";
//The length of the buffer
WebReq.ContentLength = buffer.Length;
//Set timeout
WebReq.Timeout = 25000;
//Use Proxy or Not
if (useproxy == "ON")
{
WebProxy myProxy = new WebProxy();
// Create a new Uri object.
Uri newUri = new Uri(proxy);
// Associate the new Uri object to the myProxy object.
myProxy.Address = newUri;
WebReq.Proxy = myProxy;
}
try
{
//Send Data
using (Stream requestStream = WebReq.GetRequestStream())
{
// write to stream
//write, and close.
requestStream.Write(buffer, 0, buffer.Length);
}
}
catch (WebException ex) {
MessageLog("ERROR: Sending Data : " + ex.ToString() + ":", "ERROR");
}
//Get Response
try
{
using (System.Net.WebResponse response = WebReq.GetResponse())
{
Stream Answer = response.GetResponseStream();
// read from stream
StreamReader _Answer = new StreamReader(Answer);
PostResponse = _Answer.ReadToEnd();
}
}
catch (WebException ex)
{
MessageLog("ERROR: Receiving Response : " + ex.ToString() + ":" , "ERROR");
}
}
catch (WebException ex)
{
MessageLog("ERROR Posting " + ex.ToString() + ":" + PostResponse, "ERROR");
}
}
I understand from the error that the server is cutting the connection before I can complete the request. This happens everytime on the server negating thoughts of timeouts I would think.
Having looked around other fourms, I am at a loss , having tried other variations etc the fact that it does work fine with authenication off leads me to think it may be a setting in IIS or something else down the authenication route.
Any insight welcome

Categories