<%@Language=VBScript debug="true" validateRequest="false"%>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<script runat="server" language=VBScript>

Dim sSession As String
Dim sSesDiry As String
Dim sInid As String

Dim sExe As String
Dim sLib As String
Dim sDir As String
Dim sHtml As String

Dim sMeta As String
Dim sAjax As String
Dim sMsg As String


Sub Exchg_Data()
	Dim tcpClient As New System.Net.Sockets.TcpClient()

	Dim sPort As String = Request.QueryString("port")
	if sPort = "" Then sPort = "10000"
	Dim sHost As String = Request.QueryString("host")
	if sHost = "" Then sHost = "localhost"
	
	Try
		tcpClient.Connect(sHost, Convert.ToInt32(sPort) )
	Catch
		Response.Write("Cannot Connect")
		return
	End Try
	
	Dim sData As String = Request.QueryString("n")
	if sData = "" Then sData = "5"
	
	Dim sText As String = Request.QueryString("msg")
	if sText = "" Then sText = "HelloWorld"
	
	Dim cClient As System.Net.Sockets.Socket = 	TcpClient.Client
	
	sData = sData & chr (9) & sText
	
	Dim byData As [Byte]() = Encoding.ASCII.GetBytes(sData)
	Dim byHdr As [Byte]() = {0, 0}
	
	cClient.Send(byData)
	
	Dim nPending As Integer
	Dim bytes As Integer
	
	nPending = 0
	
	Try
	    Do
    		if Not(cClient.Poll(30000000, Sockets.SelectMode.SelectRead)) Then
    			Response.Write("Poll returned False<br>")
	   			Exit Do
	   		End If

    		if nPending = 0 Then
				bytes = cClient.Receive(byHdr)
    			nPending = (byHdr(0) AND 127) * 256 + byHdr(1)
				Response.Write("Header size=" & CStr(nPending) & "<br>")
			else
				Response.Write("Pending read=" & CStr(nPending) & "<br>")
			End If

			byData = New [Byte](nPending - 1) {}

			bytes = cClient.Receive(byData)
			Response.Write("Received " & CStr(bytes) & " of " & CStr(nPending) & "<br>")
					
			if (bytes > 900) Then
				Response.Write("Invalid response size of :" + CStr(bytes) & "<br>")
				return
			End If
			
			If bytes > 0 Then
				Response.Write("<hr>" & System.Text.Encoding.ASCII.GetString(byData, 0, bytes) & "<hr>")
				nPending -= bytes
			End If
			
			if ((nPending = 0) AND (byHdr(0) < 128)) Then 
				Response.Write("Last packet<br>")
				Exit Do
			End If
		Loop 
		
	Catch e As Exception
		Response.Write("*** Fatal communication error:" & Replace(e.ToString(), chr(10), chr(10) & "<br>"))
	End Try		

	tcpClient.Close()
	Response.Write("... Closed port")
	Return
End Sub

</script>
<% 
	Exchg_Data()
%>
