I created a simple webserver that serves HTML files when you connect to it.
I created a simple form, now how come I get the form paramaters, I tried to keep reading from the request but I can't find it..
That's all I can read:
The code I use to read from the client:
while(true)
{
Console.WriteLine("Waiting for next request...");
TcpClient client = listener.AcceptTcpClient();
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
try
{
string req = sr.ReadLine();
for(int i = 0; i < 11; i++) {
string header = sr.ReadLine();
Console.WriteLine(header);
}
string[] toks = req.Split(' ');
Console.WriteLine("");
Console.WriteLine("Request Method: " + toks[0]);
Console.WriteLine("Request File: " + toks[1]);
Console.WriteLine("Response: " + toks[2]);
Console.WriteLine("");
string page = toks[1];
//Serving files&catch comes here...
}
Related
I am trying to implement an authentication method for my program. I have a server-side program that handles authentication:
class Program
{
static TcpListener listener = new TcpListener(9120);
public const string DECRYPT_KEY = "KObOBonONoinbOClHNKYJkgIKUFkjfKcvCYckcvBBCVKcbvHHCxthjcTJYBXJahjh";
static void Main(string[] args)
{
listener.Start();
while (true)
{
if (listener.Pending())
{
new Thread(TryAuthenticate).Start();
}
}
}
static void TryAuthenticate()
{
TcpClient needsAuth = listener.AcceptTcpClient();
StreamReader sr = new StreamReader(needsAuth.GetStream());
string line = sr.ReadLine();
if (!line.StartsWith("AUTH? ")) return;
StreamReader sr2 = new StreamReader("keys.pks");
string line2;
while ((line2 = sr2.ReadLine()) != null)
{
if (line == line2)
{
new StreamWriter(needsAuth.GetStream()).WriteLine("AFFIRMATIVE");
sr.Close();
}
}
sr2.Close();
needsAuth.Close();
}
}
And on the client-side I have this code:
class Authentication
{
public static bool Authenticate(string id)
{
if (id == "dEbUg2020") return true;
TcpClient client = new TcpClient("127.0.0.1", 9120);
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.WriteLine("AUTH? " + id);
if (sr.ReadLine() == "AFFIRMATIVE")
{
sw.Close();
sr.Close();
client.Close();
return true;
}
else
{
sw.Close();
sr.Close();
client.Close();
return false;
}
}
}
I have tried debugging on both the client and the server side.
On the client-side, it starts hanging at if (sr.ReadLine() == "AFFIRMATIVE").
On the server-side, it starts hanging at string line = sr.ReadLine();.
I have done some research and it has told me that when sr.ReadLine() is expecting data but doesn't get any, it hangs until it does.
But I have sent data, and both the client/server hangs indefinitely until it crashes. I am stuck, does anyone know why this isn't working?
After writing a message with your sw StreamWriter, you need to flush it with sw.Flush(); for it to actually be sent to the other side.
So
sw.WriteLine("Some line");
sw.Flush();
Otherwise, you're not sending anything.
This code currently takes kinect Body data and writes it in an Excel Worksheet. I have another code that is able to create a TCP/IP connection between two computers. How would I best combine these two ideas?
I require this Joint String Data to be sent over the network and collected by another server computer, in real-time, not in an excel file. Do you have any suggestions ?
In other words, I have some Server code, but i want the server to listen for the Kinect String Data that the client code (Another computer) is generating and currently is writing it to a local excel file.
Client Side
...
_recordBody = !_recordBody;
if (_recordBody == false)
{
recordButton.Content = "Record";
return;
}
recordButton.Content = "Stop Recording";
currentTrackingID = 0;
// create a csv file and write file header
string currPath = System.IO.Directory.GetCurrentDirectory();
string folder = "recordings";
string recordPath = System.IO.Path.Combine(currPath, folder);
if (!Directory.Exists(recordPath))
{
Directory.CreateDirectory(recordPath);
}
timeRecordingStarted = DateTime.Now;
string filename = timeRecordingStarted.ToString("yyyy-MM-dd HH-mm-ss");
filename = filename + ".csv";
filePath = System.IO.Path.Combine(recordPath, filename);
string[] writtentext = {"time," + "headX," +
"headY," +
"headZ," +
"headS," +
"neckX," +
"neckY," +
"neckZ," +
"neckS," +
"spineShoulderX," +
"spineShoulderY," +
"spineShoulderZ," +
...
"handLeftY," +
"handLeftZ," +
"handLeftS," +
"handTipRightX," +
"handTipRightY," +
"handTipRightZ," +
"handTipRightS," +
"handTipLeftX," +
"handTipLeftY," +
"handTipLeftZ," +
"handTipLeftS"
};
File.WriteAllLines(filePath, writtentext);
...
Server Code
static TcpListener tcpListener = new TcpListener(10);
static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);
{
string theString = streamReader.ReadLine();
Console.WriteLine("Message recieved by client:" + theString);
if (theString == "exit")
break;
}
streamReader.Close();
networkStream.Close();
streamWriter.Close();
//}
}
socketForClient.Close();
Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
}
public static void Main()
{
//TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("How many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}
}
For the following code, if I request a html page containing an image, I cannot see the image in the browser. What am I doing wrong?
HERE IS C# CODE:
namespace WebServer
{
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(8080);
listener.Start();
while (true) {
Console.WriteLine("Waiting for connection...");
TcpClient Client = listener.AcceptTcpClient();
StreamReader sr = new StreamReader(Client.GetStream());
StreamWriter sw = new StreamWriter(Client.GetStream());
try
{
string request = sr.ReadLine();
Console.WriteLine(request);
string[] tokens = request.Split(' ');
string page = tokens[1];
if (page == "/") {
page = "index.htm";
}
StreamReader file = new StreamReader("../../web/"+page);
sw.WriteLine("HTTP/1.0 200 ok\n");
//send the file
string data = file.ReadLine();
while (data != null)
{
sw.WriteLine(data);
sw.Flush();
data = file.ReadLine();
}
}
catch (Exception ex)
{
//error
sw.WriteLine("HTTP/1.0 404 ok\n");
sw.WriteLine("<h1>Sorry! We could not find your file!</h1>");
sw.Flush();
}
Client.Close();
}
}
}
}
Why does this problem occur, and how can I solve it?
How can i show image and video file use in browser ?
I have a client-server type application with the server running HttpListener and the client uploading data to the server using WebClient.UploadData. The code works quite well (whith large data buffers 60K and up) except one installation where UploadData times out when data buffer size is bigger that 16384. Here is my code on the client:
internal bool UploadData(byte[] buffer, String file, String folder)
{
try
{
String uri = "http://" + GlobalData.ServerIP + ":" + GlobalData.ServerHttpPort + "/upload:";
NameValueCollection headers = new NameValueCollection();
headers.Set("Content-Type", "application/octet-stream");
headers.Set("Y-Folder", folder);
headers.Set("Y-File", file);
using (WebClient wc = new WebClient())
{
wc.Credentials = new NetworkCredential(WebUserName, WebPassword);
wc.Headers.Add(headers);
wc.UploadData(new Uri(uri), buffer);
return true;
}
}
catch (Exception ex)
{
GlobalData.ODS("Exception in UploadFile " + ex.Message);
return false;
}
}
On the server
ODS(TraceDetailLevel.Level4, "Process upload ");
HttpListenerResponse response = e.RequestContext.Response;
String disp = "";
String fil = "";
String folder = "";
Stream body = e.RequestContext.Request.InputStream;
long len64 = e.RequestContext.Request.ContentLength64;
Encoding encoding = e.RequestContext.Request.ContentEncoding;
ODS(TraceDetailLevel.Level4, "Process upload " + len64 + " bytes encoding " + encoding.EncodingName);
NameValueCollection nvp = e.RequestContext.Request.Headers;
try
{
disp = nvp["Content-Disposition"];
fil = nvp["Y-File"];
folder = nvp["Y-Folder"];
}
catch { }
BinaryReader reader = new BinaryReader(body, encoding);
byte[] data = new byte[len64];
long total = 0;
while (true)
{
int dataleft = data.Length - (int)total;
int offset = (int)total;
GlobalData.ODS("Reading binary stream offset=" + offset + " read dataleft=" + dataleft);
int cnt = reader.Read(data, offset, dataleft);
if (cnt <= 0)
{
break;
}
total += cnt;
if (len64 <= total)
{
break;
}
}
ODS(TraceDetailLevel.Level4, "Process upload: Got data "+total+" should have="+len64);
if (total == len64)
{
//process data
The code above works well on all but one installation. What is wrong?
It looks like I found the source of the problem. This one installation in question that fails my code has AVG Free Antivirus installed on a computer that runs my HTTP server code. If I disable AVG on that computer my code works. Wondering if anybody runs into similar issues with AVG.
I'm trying to read mails from my live.com account, via the POP3 protocol.
I've found the the server is pop3.live.com and the port if 995.
I'm not planning on using a pre-made library, I'm using NetworkStream and StreamReader/StreamWriter for the job. I need to figure this out. So, any of the answers given here: Reading Email using Pop3 in C# are not usefull.
It's part of a larger program, but I made a small test to see if it works. Eitherway, i'm not getting anything. Here's the code I'm using, which I think should be correct.
EDIT: this code is old, please refer to the second block problem solved.
public Program() {
string temp = "";
using(TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"),8000))) {
tc.Connect("pop3.live.com",995);
using(NetworkStream nws = tc.GetStream()) {
using(StreamReader sr = new StreamReader(nws)) {
using(StreamWriter sw = new StreamWriter(nws)) {
sw.WriteLine("USER " + user);
sw.Flush();
sw.WriteLine("PASS " + pass);
sw.Flush();
sw.WriteLine("LIST");
sw.Flush();
while(temp != ".") {
temp += sr.ReadLine();
}
}
}
}
}
Console.WriteLine(temp);
}
Visual Studio debugger constantly falls over tc.Connect("pop3.live.com",995); Which throws an "A socket operation was attempted to an unreachable network 65.55.172.253:995" error.
So, I'm sending from port 8000 on my machine to port 995, the hotmail pop3 port.
And I'm getting nothing, and I'm out of ideas.
Second block: Problem was apparently that I didn't write the quit command.
The Code:
public Program() {
string str = string.Empty;
string strTemp = string.Empty;
using(TcpClient tc = new TcpClient()) {
tc.Connect("pop3.live.com",995);
using(SslStream sl = new SslStream(tc.GetStream())) {
sl.AuthenticateAsClient("pop3.live.com");
using(StreamReader sr = new StreamReader(sl)) {
using(StreamWriter sw = new StreamWriter(sl)) {
sw.WriteLine("USER " + user);
sw.Flush();
sw.WriteLine("PASS " + pass);
sw.Flush();
sw.WriteLine("LIST");
sw.Flush();
sw.WriteLine("QUIT ");
sw.Flush();
while((strTemp = sr.ReadLine()) != null) {
if(strTemp == "." || strTemp.IndexOf("-ERR") != -1) {
break;
}
str += strTemp;
}
}
}
}
}
Console.WriteLine(str);
}
What happens if you view the Network Traffic using Wireshark? Is it sending anything at all?
Edit: I can't connect via telnet to pop3.live.com at that port either. Have you managed to successfully connect via a pop3 email client ever?