-
[resolved] resolved by atheist .NET sockets
hi,
Just a couple of questions as I have just moved from Vb6 to Visual Studio 2008.
I'm doing VB.net as I am most familiar with it. I have two questions, firstly, is it feasible to use .NET 3.5. I mean is it necessary if I can acheive all aims with .net 2.0.
I am just thinking of compatiblity here. How can I change my app to 2.0 without redesigning it.
I'm really new to this so be simple.
Also, I want to make a program that runs on port 80 and returns the same page when it is requested for. This would be C:\alert.html. This is to redirect requests. (Winsock) I do not want to open a new connection each time.
Thank you.
-
Re: [2008] winsock and feasibility
Quote:
Originally Posted by samtheman
hi,
Just a couple of questions as I have just moved from Vb6 to Visual Studio 2008.
I'm doing VB.net as I am most familiar with it. I have two questions, firstly, is it feasible to use .NET 3.5. I mean is it necessary if I can acheive all aims with .net 2.0.
I am just thinking of compatiblity here. How can I change my app to 2.0 without redesigning it.
If you're not using anything .NET 3.5-specific, then changing your application to 2.0 would be fairly simple.
Quote:
Originally Posted by samtheman
I'm really new to this so be simple.
Also, I want to make a program that runs on port 80 and returns the same page when it is requested for. This would be C:\alert.html. This is to redirect requests. (Winsock) I do not want to open a new connection each time.
Thank you.
Whats the actual question? In .NET, you should use the System.Net.Sockets.TcpListener class to listen on a specific port.
-
Re: [2008] winsock and feasibility
Sorry,
No idea how to do that. Do I add a reference or what? I'm sorry this is a completely different environment for me.
-
Re: [2008] winsock and feasibility
-
Re: [2008] winsock and feasibility
You shouldnt need to add a reference, because it should be added by default. Simply declare and use the TcpListener like any other class.
-
Re: [2008] winsock and feasibility
What atheist is trying to say is forget Winsock it should not be used in .Net. Instead .Net has a set Sockets class' you should use theres a little learning curve to get your head around it but gives you more power and flexibility than Winsock.
Have a search for .Net Sockets.
Pino
-
Re: [2008] winsock and feasibility
Hi,
Thanks, I can see about sending byte streams but I really cannot find anything to what I want to do.
Basically I want to run a WebServer on 127.0.0.0 (localhost) on port 80, and whenever it is accessed, return the same page, C:\alert.html.
So, I'm not sure how to do this but:
Code:
Public Sub Listen ( _
backlog As Integer
backlog= "80"
)
Dim instance As Socket
Dim backlog As Integer
instance.Listen(backlog)
Not sure about this, from http://msdn2.microsoft.com/en-us/library/system.net.sockets.socket.listen.aspx
-
Re: [2008] winsock and feasibility
-
Re: [2008] winsock and feasibility
On the page you linked too, there's an example on listening to a specific local port. Have you tried it?
-
Re: [2008] winsock and feasibility
I'm just not getting this, how do I respond with a web page though?
Code:
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim hostIP As IPAddress = Dns.Resolve(IPAddress.Any.ToString()).AddressList(0)
Dim ep As New IPEndPoint(hostIP, port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
End Sub 'CreateAndListen
Where do I enter port number (80)? How do I respond with a page if it occurs/is opened.
Thanks
-
Re: [2008] winsock and feasibility
Well, after calling the Listen method, the socket will listen for incoming connection attempts.
Now though, you have to call its Accept (Or AcceptAsync) method, its a blocking method that will halt the execution of any code until you receive a connection attempt, in which case it returns a socket for the newly created connection.
Since this is a blocking method, you'd do best to call it on a worker thread, OR use the AcceptAsync method.
Once you've got the socket for the newly created connection you use its receive method to receive the HTTP request. Then you use the Send method to send a HTTP response. Give it a try, I'll help you if you get stuck.
-
Re: [2008] winsock and feasibility
Ok I'll see what I can do.
-
Re: [2008] winsock and feasibility
Thanks for your help so far btw
-
Re: [2008] winsock and feasibility
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) type socket is not defined, the example comes up with errors.
-
Re: [2008] winsock and feasibility
Type IP and Type IP endpoint also not defined.
-
Re: [2008] winsock and feasibility
You need to either put this line at the top of your code:
vb Code:
Imports System.Net.Sockets
or use the full name, including namespaces:
vb Code:
Dim listenSocket As New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
-
Re: [2008] winsock and feasibility
The same goes for IPEndpoint, altough I believe thats in the System.Net namespace.
-
Re: [2008] winsock and feasibility
Localhost variable hostip already declared in current block
Imports System.Net.Sockets
Imports System.Net
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim instance As Socket
Dim backlog As Integer
Dim hostip As String
Dim port As Integer
port = "80"
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim hostIP As IPAddress = Dns.Resolve(IPAddress.Any.ToString()).AddressList(0)
Dim ep As New IPEndPoint(hostIP, port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
'CreateAndListen
End Sub
End Class
not sure now...
-
Re: [2008] winsock and feasibility
-
Re: [2008] winsock and feasibility
Well the error you're getting is due to the fact that you've got 2 variables called HostIP:
and
VB.NET Code:
Dim hostIP As IPAddress = Dns.Resolve(IPAddress.Any.ToString()).AddressList(0)
Its an error with a very simple solution, simply rename one of these variables to something unique.
You also need to go to the options (Tools menu -> Options), there expand the node "Projects and solutions" and click "VB Defaults". Set Option Strict ON.
-
Re: [2008] winsock and feasibility
Why option strict on, I will get back to you with code tommorow because I am doing backup of server now.
Thanks.
-
Re: [2008] winsock and feasibility
Quote:
Originally Posted by samtheman
Why option strict on, I will get back to you with code tommorow because I am doing backup of server now.
Thanks.
You should always write your code with option strict on. It teaches you to write your code properly, and greatly decreases the chance for surprising errors in the future.
For example, this is very wrong, and would be caught by Option Strict:
VB.NET Code:
Dim port As Integer
port = "80"
since port is an integer, you shouldnt assign "80" to it, "80" is a string literal.
-
Re: [2008] winsock and feasibility
hi, still doing backup so cant use vs2k8 but
port = "80.0" ? right?
-
Re: [2008] winsock and feasibility
Quote:
Originally Posted by samtheman
hi, still doing backup so cant use vs2k8 but
port = "80.0" ? right?
Not quite;)
port = 80
-
Re: [2008] winsock and feasibility
oh no brackets, sorry in vb6 you always needed a parenthesees. I see there's a few changes in VB.net now.
I am still backing up (just burning a few BD-r's now) as I have just finished a 300gb backup.
Will work on program tommorow.
-
Re: [2008] winsock and feasibility
k dude i really am confused here as to how i respond to the sockets, my listening doesn't even work right.
-
Re: [2008] winsock and feasibility
Alright, post your current code :)
-
Re: [2008] winsock and feasibility
lol thx
Code:
Imports System.Net.Sockets
Imports System.Net
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim instance As Socket
Dim backlog As Integer
Dim hostip As String
Dim port As Integer
port = "80"
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim hostIP As IPAddress = Dns.Resolve(IPAddress.Any.ToString()).AddressList(0)
Dim ep As New IPEndPoint(hostIP, port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
'CreateAndListen
Socket.Response fso.open "C:\Alert.html", 'byte stream input????
End Sub
End Class
-
Re: [2008] winsock and feasibility
I dont see you calling the Accept method anywhere.
Here, I've cleaned the code up for you a bit. Not added anything.
VB.NET Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim instance As Socket
Dim backlog As Integer
Dim port As Integer
port = 80
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim ep As New IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
'CreateAndListen
End Sub
-
Re: [2008] winsock and feasibility
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
Also instance variable is not used warning. Obviously I am running IIS on my Server Box which I am developing on, and so I changed port to 79 to make sure conflicts are not in effect. Still receive A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
-
Re: [2008] winsock and feasibility
There is no definition of backlog just stating that it is a variable. Basically, I want to run a small web server returning the same page on Port 80. This will only ever require one connection, however, the page may be open at multiple times. This is for Hosts redirect.
-
Re: [2008] winsock and feasibility
Also for some reason, (Fixed error now) I cannot see the Form Window when I run the app, even tried making a new form. Yes, I will want it invisible later, but I was testing the ListenSocket.Accept() with a Msgbox.
-
Re: [2008] winsock and feasibility
Odd, I have to specify me.visible = 1 onload in the code, why is this?
-
Re: [2008] winsock and feasibility
Wow, sorry for so many posts, but the form appears to be disabled, as I hover over it I get an hourglass and the CPU is 100%. Looks like a wrong turn somewhere. Here's the code I got:
(Wow now it's resumed), though it is a bit freezy
Code:
Imports System.Net.Sockets
Imports System.Net
Public Class webFilter
Private Sub webFilter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Visible = 1
Dim instance As Socket
Dim backlog As Integer
Dim port As Integer
port = 79
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim ep As New IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
'CreateAndListen
listenSocket.Accept()
MsgBox("Hi testing example")
'Try this?
'#####listenSocket.BeginSend()
'Still use FileSystemObject, open file
'#####listenSocket.BeginSendFile()
End Sub
End Class
Thanks, I am getting there.
-
Re: [VB2008] .NET sockets
The reason why the form freezes upon executing the Accept method is because it is a blocking method. All code will halt there until a connection has been made and returned, or if there's some time out. When the form is frozen, try navigating here in your browser:
localhost:79
The form will probably "unfreeze", because the accept method returns. However you need to handle what it returns;
vb Code:
instance = listenSocket.Accept()
Then you need to send whatever data you wish to send through the instance socket. Note however that you'll have to send a HTTP response back, and not just the actual file.
-
Re: [VB2008] .NET sockets
so i scrap the listenSocket.Accept() on its own and declare it with instance = listenSocket.Accept()
Hmm that doesn't make much sense, we have defined instance as the accept function but we never call it.
You were right about the 79 ( I was doing that last night to unfreeze the form)
If Instance = 1
Just pulled this off the web, what is Console.Writeline (does it write to label or straight to form)
Code:
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports Microsoft.VisualBasic
Class MyTcpListener
Public Shared Sub Main()
Dim server As TcpListener
server=nothing
Try
' Set the TcpListener on port 13000.
Dim port As Int32 = 13000
Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1")
server = New TcpListener(localAddr, port)
' Start listening for client requests.
server.Start()
' Buffer for reading data
Dim bytes(1024) As Byte
Dim data As String = Nothing
' Enter the listening loop.
While True
Console.Write("Waiting for a connection... ")
' Perform a blocking call to accept requests.
' You could also user server.AcceptSocket() here.
Dim client As TcpClient = server.AcceptTcpClient()
Console.WriteLine("Connected!")
data = Nothing
' Get a stream object for reading and writing
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
' Loop to receive all the data sent by the client.
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
' Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Console.WriteLine("Received: {0}", data)
' Process the data sent by the client.
data = data.ToUpper()
Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
' Send back a response.
stream.Write(msg, 0, msg.Length)
Console.WriteLine("Sent: {0}", data)
i = stream.Read(bytes, 0, bytes.Length)
End While
' Shutdown and end connection
client.Close()
End While
Catch e As SocketException
Console.WriteLine("SocketException: {0}", e)
Finally
server.Stop()
End Try
Console.WriteLine(ControlChars.Cr + "Hit enter to continue....")
Console.Read()
End Sub 'Main
End Class 'MyTcpListener
your one is different, using .net socket instead of tcplistener
-
Re: [VB2008] .NET sockets
Sorry noticed that it is irrellevant (a client receive), console.write is for direct write to form?
listenSocket.Send() but how do I sent the html back, I am thinking of opening the file, (Still use FSO?) and sending it through a bytestream.
-
Re: [VB2008] .NET sockets
Code:
Private Sub webFilter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Visible = 1
Dim instance As Socket
Dim backlog As Integer
Dim port As Integer
port = 79
' create the socket
Dim listenSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' bind the listening socket to the port
Dim ep As New IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), port)
listenSocket.Bind(ep)
' start listening
listenSocket.Listen(backlog)
'CreateAndListen
instance = listenSocket.Accept
instance.Accept()
MsgBox("Hi")
-
Re: [VB2008] .NET sockets
I suggest that if you are interested in socket programming, that you read these two articles from start to finish... then look through the code (it's c#, but easy enough to convert if u need it in VB:P).
They explain everything u'll need to know to get up and running.. and the code works really well.
Part 1:
http://www.codeguru.com/Csharp/Cshar...cle.php/c7695/
Part 2:
http://www.codeguru.com/csharp/cshar...cle.php/c8781/
nJoy:wave:
-
Re: [VB2008] .NET sockets
-
Re: [VB2008] .NET sockets
Have gained minimal knowledge as c#, not .net sockets. This is not what I want to achieve, can you help?
-
Re: [VB2008] .NET sockets
Alright, here I'll give you some base code to play around with.
listenSocket is the main socket, the one that does all the listening. It is declared at class level, so that it doesnt goes out of scope until the form is closed.
It calls the Accept method on a different thread, in order to avoid blocking the main thread.
Make sure you understand all of this code before you continue. Dont hesitate to ask questions.
(This could be done simpler using the TcpClient/TcpListener classes, but I'll go for the Socket class)
VB.NET Code:
Option Strict On
Public Class Form1
Private listenThread As System.Threading.Thread
Private listenSocket As System.Net.Sockets.Socket
Private Const PORT_NUMBER As Integer = 80
Private Const BACKLOG As Integer = 10
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
listenSocket = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
listenSocket.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), PORT_NUMBER)) ' Bind the socket to 127.0.0.1:PORT_NUMBER
listenSocket.Listen(BACKLOG) ' Start listening on the port
listenThread = New System.Threading.Thread(AddressOf doListen) ' Create the thread that will be used for listening and responding
listenThread.IsBackground = True ' Set IsBackground to true to make the thread terminate when the main thread terminates.
listenThread.Start() ' Start the the thread
End Sub
Private Sub doListen()
Dim client As System.Net.Sockets.Socket
Do
client = listenSocket.Accept() ' When this method returns, "client" will hold the connection to the remote host.
' Send the data here, using the client.Send method.
Loop
End Sub
End Class
As you can see, this is a very simple piece of code, altough the only thing you need to implement now is sending the reply back to the client.
Are you looking to send different responses depending on what the client requests?
-
Re: [VB2008] .NET sockets
hi,
lol a bit confused. I have two questions:
1. By declaring in class do you mean the Imports. I gather this is what you mean.
2. What does console.writeline do? (off topic)
3. Sorry, said I had two, this does not open a new connection every time right, I will only ever return one page.
In answer to your question, I only will ever return a single page that is static. SO like a webserver but returning the same page. E.g http://localhost/ returns the same page as http://localhost/even-if-i-type-a-url-in-here.html
Thanks
-
Re: [VB2008] .NET sockets
noticed how the prog doesn't freeze anymore, great. Backlog is number of concurrent connections allowed? Will I need more than one connection if the page may be accessed more than once at a time. What would happen if say I needed 3 cons and only provided one, I would get a page cannot be displayed right.
-
Re: [VB2008] .NET sockets
Small problem:
set msgbox to display on connection to port, works fine. but if i refresh the page it does not happen again.
I noticed the Do Listen, what is calling the subroutine on connection, i see no reference to it.
Edit: I should place Client.Close, now I think it may be working.
-
Re: [VB2008] .NET sockets
I have no idea how to listen.Send. The subroutine is never called so how the accept occurs i do not understand. I understand listen=accept, so listen.Send would be a send on accept but do not understand how I can send my file.
C:\alert.html as a byte stream i presume
-
Re: [VB2008] .NET sockets
Code:
Dim msg As String = "Sending data to client"
client.Send(msg, 100, 80)
I get an error with option strict on, IE now declares an unknown protocol, looks like I'm getting there. I see Sub Declared when you created a new thread, by new thread do you mean process separate from the main app.
so do i open html file with fso as msg and then just Client.Send(msg,100,80)
Thanks
-
Re: [VB2008] .NET sockets
You need to send a HTTP response.
Here's a function I've written for you that'll give you a HTTP request as a byte array:
VB.NET Code:
Private Function BuildResponse(ByVal file As String) As Byte()
Dim response As New System.Text.StringBuilder
Dim sReader As System.IO.StreamReader
Dim fileContents As String
If System.IO.File.Exists(file) Then
sReader = New System.IO.StreamReader(file)
fileContents = sReader.ReadToEnd()
response.AppendLine("HTTP/1.1 200 OK")
response.AppendLine("Content-type: text/html") ' You might want to make this dynamical if you are ever going to use this in a more "dynamic" situation
response.Append("Content-Length: ")
response.AppendLine(fileContents.Length.ToString())
response.Append(Environment.NewLine)
response.Append(fileContents)
sReader.Close()
Else
response.AppendLine("HTTP/1.1 404")
response.Append(Environment.NewLine)
End If
Return System.Text.Encoding.UTF8.GetBytes(response.ToString())
End Function
Call this function, pass the file you wish to send to it, then send the returned byte array using Client.Send.
Note that this function is not the ultimate way to go about this. (It can only send documents that is not in binary format, ie text-documents, html-documents etc. And it would be more memory efficient to read and send the file sequentially in parts.)
-
Re: [VB2008] .NET sockets
Can you answer my previous questions, will I be able to access two pages of this at the same time.
What is console.writeline
Memory usage/resources is a priority - i want to use no more than 32mb of ram.
-
Re: [VB2008] .NET sockets
Code:
Option Strict On
Imports System.Net.Sockets
Imports System.Net
Public Class webFilter
Private listenThread As System.Threading.Thread
Private listenSocket As System.Net.Sockets.Socket
Private Const PORT_NUMBER As Integer = 79
Private Const BACKLOG As Integer = 10
Private Sub webFilter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
listenSocket = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
listenSocket.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), PORT_NUMBER)) ' Bind the socket to 127.0.0.1:PORT_NUMBER
listenSocket.Listen(BACKLOG) ' Start listening on the port
listenThread = New System.Threading.Thread(AddressOf doListen) ' Create the thread that will be used for listening and responding
listenThread.IsBackground = True ' Set IsBackground to true to make the thread terminate when the main thread terminates.
listenThread.Start() ' Start the the thread
End Sub
Private Sub doListen()
Dim client As System.Net.Sockets.Socket
Do
client = listenSocket.Accept() ' When this method returns, "client" will hold the connection to the remote host.
' Send the data here, using the client.Send method.
Call BuildResponse("C:\page.html")
client.Send(Response)
client.Close()
Loop
End Sub
Private Function BuildResponse(ByVal file As String) As Byte()
Dim response As New System.Text.StringBuilder
Dim sReader As System.IO.StreamReader
Dim fileContents As String
If System.IO.File.Exists(file) Then
sReader = New System.IO.StreamReader(file)
fileContents = sReader.ReadToEnd()
response.AppendLine("HTTP/1.1 200 OK")
response.AppendLine("Content-type: text/html") ' You might want to make this dynamical if you are ever going to use this in a more "dynamic" situation
response.Append("Content-Length: ")
response.AppendLine(fileContents.Length.ToString())
response.Append(Environment.NewLine)
response.Append(fileContents)
sReader.Close()
Else
response.AppendLine("HTTP/1.1 404")
response.Append(Environment.NewLine)
End If
Return System.Text.Encoding.UTF8.GetBytes(response.ToString())
End Function
End Class
Should that work? Unfortunately Response claims to not be declared as it is only declared after the function is performed. Should I define it on load?
Why are you defining some variables with Dim and some with Constant, I thought constant was for integers.
-
Re: [VB2008] .NET sockets
Quote:
Originally Posted by samtheman
Can you answer my previous questions, will I be able to access two pages of this at the same time.
No, as of currently, there is only one thread that handles all the host- replying. So during the tiny bit of time it takes to reply to one host, the others will have to wait. You'll have to spawn a new thread directly after the Accept method, pass the new connection to the thread and reply on this separate thread, in order to be able to reply to several hosts at once.
Quote:
Originally Posted by samtheman
What is console.writeline
When you create console applications, Console.WriteLine is used to write one line of text to the standard output stream (that is, the console window).
Quote:
Originally Posted by samtheman
Memory usage/resources is a priority - i want to use no more than 32mb of ram.
No as of currently,
Well, it should be no problem to send files the way I showed you in my last post, unless you're planning to send a really large file to the hosts.
-
Re: [VB2008] .NET sockets
Quote:
Originally Posted by samtheman
Code:
Option Strict On
Imports System.Net.Sockets
Imports System.Net
Public Class webFilter
Private listenThread As System.Threading.Thread
Private listenSocket As System.Net.Sockets.Socket
Private Const PORT_NUMBER As Integer = 79
Private Const BACKLOG As Integer = 10
Private Sub webFilter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
listenSocket = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
listenSocket.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), PORT_NUMBER)) ' Bind the socket to 127.0.0.1:PORT_NUMBER
listenSocket.Listen(BACKLOG) ' Start listening on the port
listenThread = New System.Threading.Thread(AddressOf doListen) ' Create the thread that will be used for listening and responding
listenThread.IsBackground = True ' Set IsBackground to true to make the thread terminate when the main thread terminates.
listenThread.Start() ' Start the the thread
End Sub
Private Sub doListen()
Dim client As System.Net.Sockets.Socket
Do
client = listenSocket.Accept() ' When this method returns, "client" will hold the connection to the remote host.
' Send the data here, using the client.Send method.
Call BuildResponse("C:\page.html")
client.Send(Response)
client.Close()
Loop
End Sub
Private Function BuildResponse(ByVal file As String) As Byte()
Dim response As New System.Text.StringBuilder
Dim sReader As System.IO.StreamReader
Dim fileContents As String
If System.IO.File.Exists(file) Then
sReader = New System.IO.StreamReader(file)
fileContents = sReader.ReadToEnd()
response.AppendLine("HTTP/1.1 200 OK")
response.AppendLine("Content-type: text/html") ' You might want to make this dynamical if you are ever going to use this in a more "dynamic" situation
response.Append("Content-Length: ")
response.AppendLine(fileContents.Length.ToString())
response.Append(Environment.NewLine)
response.Append(fileContents)
sReader.Close()
Else
response.AppendLine("HTTP/1.1 404")
response.Append(Environment.NewLine)
End If
Return System.Text.Encoding.UTF8.GetBytes(response.ToString())
End Function
End Class
Should that work? Unfortunately Response claims to not be declared as it is only declared after the function is performed. Should I define it on load?
You need to handle the return value of BuildResponse, like this:
VB.NET Code:
Private Sub doListen()
Dim client As System.Net.Sockets.Socket
Dim responseBytes() As Byte
Do
client = listenSocket.Accept() ' When this method returns, "client" will hold the connection to the remote host.
' Send the data here, using the client.Send method.
responseBytes = BuildResponse("C:\page.html")
client.Send(responseBytes, responseBytes.Length, Net.Sockets.SocketFlags.None)
client.Close()
Loop
End Sub
Quote:
Originally Posted by samtheman
Why are you defining some variables with Dim and some with Constant, I thought constant was for integers.
Well, since BACKLOG and PORT_NUMBER will not have their values changed anywhere during the applications lifetime, it is good practise to declare them as constants.
-
Re: [VB2008] .NET sockets
i'm sending maybe 2 kbytes html file and if i want to include images I will just put a path to c:\ in the page.
I do not mean exactly same time but if I opened up two ie windows and opened to localhost://79 would they both load 'eventually'
-
Re: [VB2008] .NET sockets
I am giving the app a test now. Hold on.
-
Re: [VB2008] .NET sockets
Ok, so it functions, great. But if I make a new tab and refresh, maybe 1/3 times it works. othertimes I get incorrect protocol or page cannot be displayed. As it is being used as a host file, it may get more than one redirect per page.
-
Re: [VB2008] .NET sockets
Quote:
Originally Posted by samtheman
i'm sending maybe 2 kbytes html file and if i want to include images I will just put a path to c:\ in the page.
See thats where you'll encounter problems.
When the browser finds that the HTML document includes images, it will send additional HTTP requests to your server requesting for these images, but since you're responding with the same page every time no matter what the request contained, no images will be returned to the browser.
Quote:
Originally Posted by samtheman
I do not mean exactly same time but if I opened up two ie windows and opened to localhost://79 would they both load 'eventually'
Yeah, you will be able to request this page how many times you want.
-
Re: [VB2008] .NET sockets
I'm not including images yet though. Just a html file with connection to server complete.
-
Re: [VB2008] .NET sockets
127.0.0.1 or ip address doesn't work but localhost does. Noticed I get an error unless I specify http:// will this be ok when I apply it to a hosts file.
edit: yes it will.
-
Re: [VB2008] .NET sockets
-
Re: [VB2008] .NET sockets
net Explorer cannot display the webpage
Most likely causes:
You are not connected to the Internet.
The website is encountering problems.
There might be a typing error in the address.
Occurs if I open up more than one 127.0.0.1. Even if done after 5 seconds of previous request, takes a couple of refreshes to fix this. Anyway I can fix this, simply by increasing number of connections to say 10?