I have a WebSocket created with HTML5 and Javascript, and i'm trying to connect it using Winsock configured in VB6, WebSocket is communicating with the Winsock and WebSocket connection is still in the Connecting stage, and not connecting, seems i have a problem in Handshaking with the WebSocketm. Please help me to find the problem with my code
My vb6 code as bellow
Private Sub Form_Load()
Winsock1.LocalPort = 6701
Winsock1.Listen
End Sub
Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
Winsock1(Index).Close
Winsock1(Index).Accept requestID
Dim Packet As String
With Winsock1(Index)
Packet = "HTTP/1.1 101 Web Socket Protocol Handshake" & vbNewLine
Packet = Packet & "Upgrade: WebSocket" & vbNewLine
Packet = Packet & "Connection: Upgrade" & vbNewLine
Packet = Packet & "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=" & vbNewLine
Data = Empty
.SendData Packet
End With
End Sub
Private Sub Winsock1_DataArrival(Index As Integer, ByVal bytesTotal As Long)
Dim sData As String
Winsock1(Index).GetData sData
txtText1.Text = sData
End Sub
and sample WebScocket html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function connect() {
var ws = new WebSocket("ws://127.0.0.1:6701");
ws.onopen = function () {
console.log('open ');
};
ws.onmessage = function (evt) {
console.log("About to receive data");
var received_msg = evt.data;
console.log("Message received = " + received_msg);
};
ws.onclose = function () {
// websocket is closed.
console.log("Connection is closed...");
};
};
</script>
</head>
<body style="font-size:xx-large" >
<div>
Click here to start</div>
</body>
</html>
Related
I am dynamically building a datatable and binding it to a gridview in a VB codebehind. I transform the gridview cell data into LinkButton controls to allow that data to be clicked for updates.
I am using AjaxControlToolkit to present a modal popup to collect data updates. Once those updates are completed, I rebuild the datatable and databind the gridview. In Gridview.RowCreated, I repeat the creation of the LinkButton controls on postback.
When the page is presented following an update, when I click on a LinkButton the postback happens but RowCommand is not fired. While debugging, I notice that when this occurs, Page.FindControl() cannot locate the targeted LinkButton control.
The page is returned without firing the RowCommand event to trigger the display of the modal popup. If I simply press the LinkButton a second time, the LinkButton control can be found using Page.FindControl() and RowCommand fires as desired.
What am I missing? Thanks much for any ideas to resolve this issue. I have struggled with this all day and I'm running out of ideas.
Thank you!
Here is requested code:
<asp:GridView ID="CustomeGridview" GridLines="Vertical" Width="100%" runat="server"
BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" AutoGenerateColumns="true" ForeColor="Black" ShowHeader="False" Font-Names="Verdana"
Font-Size="11px" OnRowCommand="CustomeGridview_RowCommand"
OnRowDataBound="CustomeGridview_RowDataBound">
<FooterStyle BackColor="#CCCCCC" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.CacheControl = "no-cache"
Response.Expires = -1
Response.AddHeader("Pragma", "no-cache")
If Page.IsPostBack = False Then
ViewState("Left") = 3
ViewState("Right") = 6
generateManualDt()
Else
Dim controlName As String = Request.Params.Get("__EVENTTARGET")
Dim ctl As Control = Page.FindControl(controlName)
End If
Page_Header_Label.Text = "Action Qualification Matrix - " & Session("CurrentServiceName")
FormatColumns()
End Sub
Public Sub generateManualDt()
Dim ManualDt As DataTable = BuildMainDataTable()
ViewState("ManualDt") = ManualDt
CustomeGridview.DataSource = ManualDt
CustomeGridview.DataBind()
SetJumpScrollButtons()
End Sub
Protected Sub CustomeGridview_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CustomeGridview.RowDataBound
Dim dt As DataTable = DirectCast(ViewState("ManualDt"), DataTable)
Dim dtsnocol As DataTable = DirectCast(ViewState("dtsnocol"), DataTable)
If e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header Then
For gvCol As Integer = 7 To dt.Columns.Count - 1
e.Row.Cells(gvCol).Visible = False
Next
SetupGridRowControls(e, dtsnocol, dt)
End If
End Sub
Protected Sub CustomeGridview_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles CustomeGridview.RowCreated
Dim dt As DataTable = DirectCast(ViewState("ManualDt"), DataTable)
Dim dtsnocol As DataTable = DirectCast(ViewState("dtsnocol"), DataTable)
e.Row.Cells(0).Visible = False ' Hide the QuestionID column
If Page.IsPostBack Then
If e.Row.RowType = DataControlRowType.DataRow OrElse e.Row.RowType = DataControlRowType.Header Then
SetupGridRowControls(e, dtsnocol, dt)
End If
End If
End Sub
Private Sub SetupGridRowControls(ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs, ByRef dtsnocol As DataTable, ByRef mainDt As DataTable)
Dim CurrSnoCount As Integer = 0
If Not dtsnocol Is Nothing Then
CurrSnoCount = dtsnocol.Rows.Count
End If
If e.Row.DataItemIndex = 0 Then ' Scenario Number row
Dim snoLabel As New Label()
snoLabel.Text = "SCENARIO "
snoLabel.ID = "snoHdrLabel"
e.Row.Cells(2).Controls.Add(snoLabel)
Dim addScenarioBtn = buildAddButton("AddScenario", "", "Click to add a new scenario column")
e.Row.Cells(2).Controls.Add(addScenarioBtn)
ElseIf e.Row.DataItemIndex = 1 Then ' Question Header and Sno Descriptions
Dim questLabel As New Label()
questLabel.Text = "QUESTIONS "
questLabel.ID = "questdrLabel"
e.Row.Cells(2).Controls.Add(questLabel)
Dim addQuestionBtn = buildAddButton("AddQuestion", "", "Click to add a new question row")
e.Row.Cells(2).Controls.Add(addQuestionBtn)
Dim cellText As String = ""
Dim snoId As String = ""
For snoRowIdx As Integer = 0 To CurrSnoCount - 1
snoId = dtsnocol.Rows(snoRowIdx)("ScenarioID").ToString()
cellText = dtsnocol.Rows(snoRowIdx)("Note").ToString()
Dim lnkBtn = buildLinkButton("EditScenario", snoId, cellText)
e.Row.Cells(snoRowIdx + 3).Controls.Add(lnkBtn)
Next
ElseIf e.Row.DataItemIndex > 1 Then ' Question / Responses
Dim cellText As String = ""
Dim cellAddr As String = ""
Dim snoId As String = ""
Dim questId As String = mainDt.Rows(e.Row.DataItemIndex).Item(0).ToString.Trim
For snoRowIdx As Integer = 0 To CurrSnoCount - 1
snoId = dtsnocol.Rows(snoRowIdx)("ScenarioID").ToString.Trim
cellAddr = String.Format("{0}:{1}", questId, snoId)
cellText = mainDt.Rows(e.Row.DataItemIndex).Item(snoRowIdx + 3).ToString.Trim
Dim lnkBtn = buildLinkButton("EditResponses", cellAddr, cellText)
e.Row.Cells(snoRowIdx + 3).Controls.Add(lnkBtn)
Next
End If
End Sub
Private Function buildLinkButton(ByVal linkCmd As String, ByVal linkCmdArg As String, ByVal linkText As String) As LinkButton
Dim lnkBtn As New LinkButton()
lnkBtn.Text = linkText
lnkBtn.CommandName = linkCmd
lnkBtn.CommandArgument = linkCmdArg
lnkBtn.ToolTip = "Click to update"
lnkBtn.CssClass = "cell_link"
Return lnkBtn
End Function
Private Function buildAddButton(ByVal btnCmd As String, ByVal btnCmdArg As String, ByVal btnToolTip As String) As ImageButton
Dim imgBtn As New ImageButton()
imgBtn.CommandName = btnCmd
imgBtn.CommandArgument = btnCmdArg
imgBtn.ImageUrl = "~/Images/services/SmallAddBtn.gif"
imgBtn.ToolTip = btnToolTip
imgBtn.ID = String.Format("{0}_GenImageButton", btnCmd)
Return imgBtn
End Function
I want to call java servlet from from my vb 6.0 code. I have tu use the URL of the servelet on remote machine and display the message after execution of the program.
Private Sub Command3_Click()
Dim req As WinHttp.WinHttpRequest
Dim buffer As Variant
Set req = New WinHttp.WinHttpRequest
req.SetTimeouts 1800000, 1800000, 1800000, 1800000
req.Open "POST", "http://www.google.co.in", False
buffer = "tusharp 0"
req.Send cmbuffer
Debug.Print req.ResponseText
End Sub
Try this.....
Using following bunch of code you can simply call servlet by using URL. You can pass parameters via appropriate method.
**Private Function ExecuteSQL(ByVal sSQL As String, ByVal bResultSet As Boolean) As String
Dim http As Object
Dim strURL As String
Dim strPostData As String
Dim strHeader As String
Dim strResponse As String
On Error GoTo Err
Screen.MousePointer = vbHourglass
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
strPostData = "?Command=" & IIf(bResultSet, "SELECT", "UPDATE") & "&SQL=" & sSQL
strURL = "http://localhost:8080/FirstProject/DBConnector" & strPostData
http.setTimeouts 10000, 10000, 10000, 10000 'For some reason times out sooner than this sometimes
http.Open "POST", strURL, False
http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
http.Send strPostData
strResponse = http.ResponseText
Screen.MousePointer = vbDefault
ExecuteSQL = strResponse
Exit Function
I am trying to learn about websocket functionality supported by Opera browser. I got some sample code from web.
Is it possible to connect to a simple c echo server (not using web server) serving on some port (say 9999) from Opera 12.x browser using websockets? I tried this but is not working. I am getting disconnected error in browser with ERROR: undefined. At Linux echo server side, it is getting a connect request, accepting it, but not able to read any data.
I am loading the test page locally not from any web server.
If simple echo server is not sufficient, is it possible to enhance the simple echo server to return HTTP response and make it work. Basically I am trying to use websockets interfaces from browser to connect to a server without using any web server.
Thanks,
raj
websocket client (Copied from http://www.websocket.org/echo.html)
<!DOCTYPE html>
<meta charset="utf-8" />
<script language="javascript" type="text/javascript">
var wsUri = "ws://192.168.100.2:9999/";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<div id="output"></div>
</html>
Echo Server(copied from http://www.cs.utah.edu/~swalton/listings/sockets/programs/part2/chap6/simple-server.c)
.
.
#define MY_PORT 9999
#define MAXBUF 1024
int main(int Count, char *Strings[])
{ int sockfd;
struct sockaddr_in self;
char buffer[MAXBUF];
/*---Create streaming socket---*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("Socket");
exit(errno);
}
/*---Initialize address/port structure---*/
bzero(&self, sizeof(self));
self.sin_family = AF_INET;
self.sin_port = htons(MY_PORT);
self.sin_addr.s_addr = INADDR_ANY;
/*---Assign a port number to the socket---*/
if ( bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0 )
{
perror("socket--bind");
exit(errno);
}
/*---Make it a "listening socket"---*/
if ( listen(sockfd, 20) != 0 )
{
perror("socket--listen");
exit(errno);
}
/*---Forever... ---*/
while (1)
{ int clientfd;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
/*---accept a connection (creating a data pipe)---*/
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
printf("Received %d\n", recv(clientfd, buffer, MAXBUF, 0));
printf("Date %s\n\n", buffer);
/*---Echo back anything sent---*/
send(clientfd, buffer, recv(clientfd, buffer, MAXBUF, 0), 0);
/*---Close data connection---*/
close(clientfd);
}
.
.
.
The WebSocket protocol is not a raw TCP socket connection. You're server must also support the WebSocket protocol.
There is a online WebSockets echo service at http://www.websocket.org/echo.html
If you really want to connect from WebSockets to a raw socket server you can use websockify to bridge between the two. Disclaimer: I made websockify.
I have a page for deleting ORDER record. This page was called from AJAX, which work perfectly. However once I added some code that I made for updating inventory table at the same time. It seemed that AJAX function became malfunction and I can't figure out what is wrong with them. Please suggest me. Thanks in advance.
My AJAX function (order_edit.asp)
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax(ID) { // delete order
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
var url = '../engine/delorder_edit.asp';
var pmeters = "tID="+ID;
var bill_id = document.getElementById('bill_id').value; // additional for delorder_edit.asp
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
document.getElementById("tr"+ID).style.display = 'none';
}
}
}
}
</script>
My delorder_edit.asp Page
<%
Option Explicit
Dim strID
strID = Request.Form("tID")
Dim Conn,strSQL,objExec
Set Conn = Server.Createobject("ADODB.Connection")
Conn.Open "DRIVER=Microsoft Access Driver (*.mdb);DBQ=" & Server.MapPath("../database/TKP.mdb"),"" , ""
'********** *****************************
'Open recorset in order to add od_qty back to tbl_inventory before this record was removed
'****** Once I added these code, my ajax became malfunction ******
Set rsOrder = conn.Execute("SELECT * FROM tbl_order WHERE od_id = "&strID&"" )
pd_id = rsOrder.fields.item("pd_id")
od_qty = rsOrder.fields.item("od_qty")
od_qty = DzToPcs(od_qty)
strSQL1 = "UPDATE tbl_inventory SET inv_qty_act = inv_qty_act + " & od_qty & ", inv_date = date() WHERE pd_id = '" & pd_id & "'"
Set objExec = Conn.Execute(sql1)
'*******************************************
strSQL = ""
strSQL = strSQL&"DELETE * FROM tbl_order "
strSQL = strSQL&"WHERE od_id = "&strID&" "
Set objExec = Conn.Execute(strSQL)
If Err.Number = 0 Then
Response.write("Y")
Else
Response.write("N")
End IF
Conn.Close()
Set Conn = Nothing
%>
First of all i will suggest to use the jQuery.ajax method to call the server method, so your code will be less and also more convenience to understand. And second thing, debug :
"HttPRequest.onreadystatechange = function()",
and check what value is being returned. Until unless we didn't get a exact error we can not suggest you a solution.
How do I use proxies with HAP? This is what I have so far...(with no luck).
IPCHICKEN is just used to test the ip address. it is showing my ip address and not the ip address of my proxy
Function GetPrice(ByVal AmazonURL As String, ByVal Delay As Integer)
Dim aHtml As New HtmlWeb
Dim ChromeAgent As String = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"
aHtml.UserAgent = ChromeAgent
Dim proxy As New System.Net.WebProxy
Dim proxyAddress As New Uri("http://111.111.111/")
Dim aDoc As HtmlDocument = aHtml.Load("http://www.ipchicken.com", "GET", proxy, System.Net.CredentialCache.DefaultCredentials)
Dim aNode As HtmlAgilityPack.HtmlNode
aNode = aDoc.DocumentNode.SelectSingleNode("//div[#id='olpDivId']/span[2]")
If aNode.InnerText Is Nothing Then
End If
Dim UsedPrice1 As String = aNode.InnerText
Dim i As Integer = UsedPrice1.IndexOf("$")
Dim UsedPrice As Integer = UsedPrice1.Substring(i + 1)
System.Threading.Thread.Sleep(Delay)
Return UsedPrice
End Function
Maybe try something like the following. Depending on the page you mightn't need the UTF8 conversion.
WebProxy proxy = new WebProxy("proxyname", 8080);
proxy.Credentials = CredentialCache.DefaultCredentials;
WebClient client = new WebClient();
client.Proxy = proxy;
string baseHtml = "";
byte[] pageContent = client.DownloadData("your target url");
UTF8Encoding utf = new UTF8Encoding();
baseHtml = utf.GetString(pageContent);
HtmlDocument pageHtml = new HtmlDocument();
pageHtml.LoadHtml(baseHtml);