473,385 Members | 1,944 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Socket server error.


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
6 1864
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
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

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

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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Rune | last post by:
Hi, I've written a very simple 'kill-server' to help me shut down processes through Telnet or HTTP. The kill-server is a function and is launched as a thread. I use the module socket.py on Python...
11
by: anuradha.k.r | last post by:
hi, i am writing a socket program in python,both client side and server side.I've written the client side which is working perfectly fine(checked it against server program written in C).but as for...
2
by: Rene Sørensen | last post by:
We are 4 students working on a assignment, that our teacher gave use, normally we do this is C++, but the 4 of us, use C# more often that C++ so… We made a small games called reversi, now our job...
7
by: | last post by:
Hi all, I have a simple .aspx page running on net 2.0 that is trying to do a http post to a remote server. Here is the code Private Function ProcessRequests(ByVal strbody As String) As String...
1
by: bobano | last post by:
Hi everyone, I am writing a POP3 Client program in Perl. You connect to a POP3 Server and have a running conversation with the mail server using commands from the RFC 1939 Post Office Protocol....
2
by: Vitali Gontsharuk | last post by:
Hi! I have a problem programming a simple client-server game, which is called pingpong ;-) The final program will first be started as a server (nr. 2) and then as a client. The client then...
14
by: ahlongxp | last post by:
Hi, everyone, I'm implementing a simple client/server protocol. Now I've got a situation: client will send server command,header paires and optionally body. server checks headers and decides...
1
by: orehian | last post by:
Construct a one-time password system. · Write a server code and a client code. The server code takes as input a username and a one-time password from the client and then sends a message...
2
by: manasap | last post by:
Hi all! I've written a server and a client application using asynchronous sockets.The client sends data packets for every 7 seconds.The server receives the packets. This process proceeds...
0
by: kuguy | last post by:
Hi all, I'm new to the forums, so I hope this isn't in the wrong place... I have that "Software caused connection abort: socket write error" exception error that i've never meet before. ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.