By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,306 Members | 1,657 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,306 IT Pros & Developers. It's quick & easy.

Socket server error.

P: n/a

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);
}
}
Nov 7 '06 #1
Share this Question
Share on Google+
6 Replies


P: n/a
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!

"Vadym Stetsyak" <va*****@ukr.netwrote in message
news:eu**************@TK2MSFTNGP04.phx.gbl...
Hello, kikapu!

If client uses WinHttp then, IMO, it sends HTTP request?
And if that's true, server has to respond with valid HTTP response.

Have a look at the following RFC that describes HTTP protocol
( http://www.w3.org/Protocols/rfc2616/rfc2616.html )

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

kThe string is succesfully sent to the server but not the reverse when
kthe
kserver just replies with a string.
kThe client reports (last dll error) that "the server returned an
kinvalid or
kunrecognized response".

kAm i doing something wrong with the writing to network stream (neede
kheaders
kor something else) ??

kThanks for any help

khere it is:

kusing System;
kusing System.Net.Sockets;
kusing System.IO;

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

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

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com

Nov 7 '06 #2

P: n/a
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.
================================================== ====

Nov 8 '06 #3

P: n/a

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[MSFT]" <ch******@online.microsoft.comwrote in message
news:Do**************@TK2MSFTNGXA01.phx.gbl...
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.
================================================== ====

Nov 8 '06 #4

P: n/a
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

Nov 9 '06 #5

P: n/a

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...)

"Charles Wang[MSFT]" <ch******@online.microsoft.comwrote in message
news:HW**************@TK2MSFTNGXA01.phx.gbl...
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

Nov 9 '06 #6

P: n/a
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.
================================================== ====

Nov 10 '06 #7

This discussion thread is closed

Replies have been disabled for this discussion.