Socket server error.

K

kikapu

Hi to all,

i have the following simple Socket Server code and a vb client that send to
it some data using
WinHttp. (very simple code, just open and send)

The string is succesfully sent to the server but not the reverse when the
server just replies with a string.
The client reports (last dll error) that "the server returned an invalid or
unrecognized response".

Am i doing something wrong with the writing to network stream (neede headers
or something else) ??

Thanks for any help



here it is:

using System;
using System.Net.Sockets;
using System.IO;

public class AsynchIOServer
{
public static void Main() {
TcpListener tcpListener = new TcpListener(8501);
tcpListener.Start();
Console.WriteLine("started listening...");
while (true) {
Socket socketForClient = tcpListener.AcceptSocket();

if (socketForClient.Connected) {
Console.WriteLine("Client connected");
NetworkStream networkStream = new
NetworkStream(socketForClient);
StreamWriter streamWriter = new
System.IO.StreamWriter(networkStream);
StreamReader streamReader = new
System.IO.StreamReader(networkStream);
string theString = "Sending";
streamWriter.WriteLine(theString);
Console.WriteLine(theString);
streamWriter.Flush();
theString = streamReader.ReadLine();
Console.WriteLine(theString);
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Shutdown(SocketShutdown.Send);
socketForClient.Disconnect(false);
}
}
 
K

kikapu

Hello Vadym !

Yes, client uses WinHttp and send an http request.
I will look at your link you gave me.
I just do not know how i can return the simple world "Ok" back to the
http req originator and make sure that he understand it...

thanks again!
 
C

Charles Wang[MSFT]

Hi Kikapu,
Thanks for using Microsoft Managed Newsgroup.

Vadym's direction is accurate. The http response header need to be
implemented by yourself.
For now, I want to provide a more direct way for you.
The following code snippet that I had found from internet is used to setup
a web server and I would like to share it with you:
//////////webserver.cs//////////////////
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading ;


class MyWebServer
{

private TcpListener myListener ;
private int port = 8080 ;

public MyWebServer()
{
try
{
myListener = new TcpListener(port) ;
myListener.Start();
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;

}
catch(Exception e)
{
Console.WriteLine("Error:" +e.ToString());
}
}
public void SendHeader(string sHttpVersion, string sMIMEHeader, int
iTotBytes, string sStatusCode, ref Socket mySocket)
{

String sBuffer = "";

if (sMIMEHeader.Length == 0 )
{
sMIMEHeader = "text/html"; // default text/html
}

sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
sBuffer = sBuffer + "Server: cx1193719-b\r\n";
sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";

Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

SendToBrowser( bSendData, ref mySocket);

Console.WriteLine("Total Bytes : " + iTotBytes.ToString());

}

public void SendToBrowser(String sData, ref Socket mySocket)
{
SendToBrowser (Encoding.ASCII.GetBytes(sData), ref mySocket);
}

public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
{
int numBytes = 0;

try
{
if (mySocket.Connected)
{
if (( numBytes = mySocket.Send(bSendData, bSendData.Length,0)) == -1)
Console.WriteLine("Socket Error cannot Send Packet");
else
{
Console.WriteLine("No. of bytes send {0}" , numBytes);
}
}
else
Console.WriteLine("Connection failure....");
}
catch (Exception e)
{
Console.WriteLine("Error : {0} ", e );

}
}
public static void Main()
{
MyWebServer MWS = new MyWebServer();
}
public void StartListen()
{

int iStartPos = 0;
String sRequest;
String sDirName;
String sRequestedFile;
String sErrorMessage;
String sLocalDir;
/////////////////////////////////////Set Virtual
directory/////////////////////////////////////
String sMyWebServerRoot = "E:\\MyWebServerRoot\\";
////////////////////////////////////////////////////////////////////////////
//////////////////////
String sPhysicalFilePath = "";
String sFormattedMessage = "";
String sResponse = "";


while(true)
{
Socket mySocket = myListener.AcceptSocket() ;

Console.WriteLine ("Socket Type " +mySocket.SocketType );
if(mySocket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nCLient IP
{0}\n",mySocket.RemoteEndPoint) ;

Byte[] bReceive = new Byte[1024] ;
int i = mySocket.Receive(bReceive,bReceive.Length,0) ;

string sBuffer = Encoding.ASCII.GetString(bReceive);


// Only deal with Get type request
if (sBuffer.Substring(0,3) != "GET" )
{
Console.WriteLine(" Only deal with Get type request...");
mySocket.Close();
return;
}

// search the postion of "HTTP"
iStartPos = sBuffer.IndexOf("HTTP",1);


string sHttpVersion = sBuffer.Substring(iStartPos,8);


// get the request type and the request path name
sRequest = sBuffer.Substring(0,iStartPos - 1);

sRequest.Replace("\\","/");


//Appen '/' to the end of the request if the end word is not a file name
and has no '/'
if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}


//Get request file name
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);


//Get request file directory
sDirName = sRequest.Substring(sRequest.IndexOf("/"),
sRequest.LastIndexOf("/")-3);


//Get virtual physical directory
sLocalDir = sMyWebServerRoot;

Console.WriteLine("Request file directory : " + sLocalDir);

if (sLocalDir.Length == 0 )
{
sErrorMessage = "<H2>Error!! Requested Directory does not exists</H2><Br>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref
mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
mySocket.Close();
continue;
}


if (sRequestedFile.Length == 0 )
{
//request for filename
sRequestedFile = "index.html";
}


/////////////////////////////////////////////////////////////////////
// Request for file type (text/html)
/////////////////////////////////////////////////////////////////////

String sMimeType = "text/html";

sPhysicalFilePath = sLocalDir + sRequestedFile;
Console.WriteLine("Request File: " + sPhysicalFilePath);


if (File.Exists(sPhysicalFilePath) == false)
{

sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref
mySocket);
SendToBrowser( sErrorMessage, ref mySocket);

Console.WriteLine(sFormattedMessage);
}

else
{
int iTotBytes=0;

sResponse ="";

FileStream fs = new FileStream(sPhysicalFilePath, FileMode.Open,
FileAccess.Read, FileShare.Read);

BinaryReader reader = new BinaryReader(fs);
byte[] bytes = new byte[fs.Length];
int read;
while((read = reader.Read(bytes, 0, bytes.Length)) != 0)
{
sResponse = sResponse + Encoding.ASCII.GetString(bytes,0,read);

iTotBytes = iTotBytes + read;

}
reader.Close();
fs.Close();

SendHeader(sHttpVersion, sMimeType, iTotBytes, " 200 OK", ref mySocket);
SendToBrowser(bytes, ref mySocket);
//mySocket.Send(bytes, bytes.Length,0);

}
mySocket.Close();
}
}
}
}

///////////-End-////////////////


Hope this helpful.
Please feel free to let me know if you have any other questions or
concerns.

Sincerely yours,
Charles Wang
Microsoft Online Community Support

======================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================
 
K

kikapu

Hi Charles,

thanks a lot for your response. Enough code to play with!

I will let you know of the result,

thanks again!


Charles Wang said:
Hi Kikapu,
Thanks for using Microsoft Managed Newsgroup.

Vadym's direction is accurate. The http response header need to be
implemented by yourself.
For now, I want to provide a more direct way for you.
The following code snippet that I had found from internet is used to setup
a web server and I would like to share it with you:
//////////webserver.cs//////////////////
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading ;


class MyWebServer
{

private TcpListener myListener ;
private int port = 8080 ;

public MyWebServer()
{
try
{
myListener = new TcpListener(port) ;
myListener.Start();
Console.WriteLine("Web Server Running... Press ^C to Stop...");
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;

}
catch(Exception e)
{
Console.WriteLine("Error:" +e.ToString());
}
}
public void SendHeader(string sHttpVersion, string sMIMEHeader, int
iTotBytes, string sStatusCode, ref Socket mySocket)
{

String sBuffer = "";

if (sMIMEHeader.Length == 0 )
{
sMIMEHeader = "text/html"; // default text/html
}

sBuffer = sBuffer + sHttpVersion + sStatusCode + "\r\n";
sBuffer = sBuffer + "Server: cx1193719-b\r\n";
sBuffer = sBuffer + "Content-Type: " + sMIMEHeader + "\r\n";
sBuffer = sBuffer + "Accept-Ranges: bytes\r\n";
sBuffer = sBuffer + "Content-Length: " + iTotBytes + "\r\n\r\n";

Byte[] bSendData = Encoding.ASCII.GetBytes(sBuffer);

SendToBrowser( bSendData, ref mySocket);

Console.WriteLine("Total Bytes : " + iTotBytes.ToString());

}

public void SendToBrowser(String sData, ref Socket mySocket)
{
SendToBrowser (Encoding.ASCII.GetBytes(sData), ref mySocket);
}

public void SendToBrowser(Byte[] bSendData, ref Socket mySocket)
{
int numBytes = 0;

try
{
if (mySocket.Connected)
{
if (( numBytes = mySocket.Send(bSendData, bSendData.Length,0)) == -1)
Console.WriteLine("Socket Error cannot Send Packet");
else
{
Console.WriteLine("No. of bytes send {0}" , numBytes);
}
}
else
Console.WriteLine("Connection failure....");
}
catch (Exception e)
{
Console.WriteLine("Error : {0} ", e );

}
}
public static void Main()
{
MyWebServer MWS = new MyWebServer();
}
public void StartListen()
{

int iStartPos = 0;
String sRequest;
String sDirName;
String sRequestedFile;
String sErrorMessage;
String sLocalDir;
/////////////////////////////////////Set Virtual
directory/////////////////////////////////////
String sMyWebServerRoot = "E:\\MyWebServerRoot\\";
////////////////////////////////////////////////////////////////////////////
//////////////////////
String sPhysicalFilePath = "";
String sFormattedMessage = "";
String sResponse = "";


while(true)
{
Socket mySocket = myListener.AcceptSocket() ;

Console.WriteLine ("Socket Type " +mySocket.SocketType );
if(mySocket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nCLient IP
{0}\n",mySocket.RemoteEndPoint) ;

Byte[] bReceive = new Byte[1024] ;
int i = mySocket.Receive(bReceive,bReceive.Length,0) ;

string sBuffer = Encoding.ASCII.GetString(bReceive);


// Only deal with Get type request
if (sBuffer.Substring(0,3) != "GET" )
{
Console.WriteLine(" Only deal with Get type request...");
mySocket.Close();
return;
}

// search the postion of "HTTP"
iStartPos = sBuffer.IndexOf("HTTP",1);


string sHttpVersion = sBuffer.Substring(iStartPos,8);


// get the request type and the request path name
sRequest = sBuffer.Substring(0,iStartPos - 1);

sRequest.Replace("\\","/");


//Appen '/' to the end of the request if the end word is not a file name
and has no '/'
if ((sRequest.IndexOf(".") <1) && (!sRequest.EndsWith("/")))
{
sRequest = sRequest + "/";
}


//Get request file name
iStartPos = sRequest.LastIndexOf("/") + 1;
sRequestedFile = sRequest.Substring(iStartPos);


//Get request file directory
sDirName = sRequest.Substring(sRequest.IndexOf("/"),
sRequest.LastIndexOf("/")-3);


//Get virtual physical directory
sLocalDir = sMyWebServerRoot;

Console.WriteLine("Request file directory : " + sLocalDir);

if (sLocalDir.Length == 0 )
{
sErrorMessage = "<H2>Error!! Requested Directory does not
exists</H2><Br>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref
mySocket);
SendToBrowser(sErrorMessage, ref mySocket);
mySocket.Close();
continue;
}


if (sRequestedFile.Length == 0 )
{
//request for filename
sRequestedFile = "index.html";
}


/////////////////////////////////////////////////////////////////////
// Request for file type (text/html)
/////////////////////////////////////////////////////////////////////

String sMimeType = "text/html";

sPhysicalFilePath = sLocalDir + sRequestedFile;
Console.WriteLine("Request File: " + sPhysicalFilePath);


if (File.Exists(sPhysicalFilePath) == false)
{

sErrorMessage = "<H2>404 Error! File Does Not Exists...</H2>";
SendHeader(sHttpVersion, "", sErrorMessage.Length, " 404 Not Found", ref
mySocket);
SendToBrowser( sErrorMessage, ref mySocket);

Console.WriteLine(sFormattedMessage);
}

else
{
int iTotBytes=0;

sResponse ="";

FileStream fs = new FileStream(sPhysicalFilePath, FileMode.Open,
FileAccess.Read, FileShare.Read);

BinaryReader reader = new BinaryReader(fs);
byte[] bytes = new byte[fs.Length];
int read;
while((read = reader.Read(bytes, 0, bytes.Length)) != 0)
{
sResponse = sResponse + Encoding.ASCII.GetString(bytes,0,read);

iTotBytes = iTotBytes + read;

}
reader.Close();
fs.Close();

SendHeader(sHttpVersion, sMimeType, iTotBytes, " 200 OK", ref mySocket);
SendToBrowser(bytes, ref mySocket);
//mySocket.Send(bytes, bytes.Length,0);

}
mySocket.Close();
}
}
}
}

///////////-End-////////////////


Hope this helpful.
Please feel free to let me know if you have any other questions or
concerns.

Sincerely yours,
Charles Wang
Microsoft Online Community Support

======================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no
rights.
======================================================
 
C

Charles Wang[MSFT]

Hi Mediatel,
You are welcome.

Just feel free to let me know if you have any other questions or concerns.

Have a great day!

Charles Wang
Microsoft Online Community Support
 
K

kikapu

Ok, i tried the example you gave me, i modified it to suit my needs on my
program and now everything
is working ok! Headers are sent correctly to Clients, wheteher thet are
browsers or socket clients.

Thanks a lot for your help! (And Vadym too, from whose link i got the Http
protocol errors...)
 
C

Charles Wang[MSFT]

Hi Mediate,

Appreciate your update and response. I am glad to hear that the problem has
been fixed. If you have any other questions or concerns, please do not
hesitate to contact us. It is always our pleasure to be of assistance.

Have a nice day!

Charles Wang
Microsoft Online Community Support

======================================================
When responding to posts, please "Reply to Group" via your newsreader
so that others may learn and benefit from this issue.
======================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
======================================================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top