我正在创建一个小应用程序,它应该可以远程控制浏览器窗口:导航、填写表单等。我正在尝试使用Chrome远程调试和C#来实现这个目标。目前的原型连接到浏览器,获取可用页面列表并建立WebSocket连接。
- Start chrome.exe --remote-debugging-port=9123
Connecto to ws://localhost:9123/devtools/page/1 and send:
request: { "id": 1, "method": "DOM.setOuterHTML", "params": {"nodeId": 1, "outerHTML": ""}}
看起来不对,但没有返回错误。
代码:
var client = new WebClient();
var pages = client.DownloadString("http://localhost:9123/json");
Console.WriteLine(pages); // works well, displays JSON with info about pages
// create WebSocket
var socket = new WebSockets.WebSocket("ws://localhost:9123/devtools/page/1");
// it should print messages to console:
socket.OnMessage += (sender, eventdata) => Console.WriteLine(eventdata);
// works well - sends and recieves handshaking messages
socket.Connect();
Console.WriteLine("\nType \"exit\" to exit.\n");
string data;
while (true)
{
Thread.Sleep(500);
Console.Write("> ");
data = Console.ReadLine();
if (data == "exit")
break;
// sends data:
socket.Send(data);
}
数据如何发送到WebSocket流中:
byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
_wsStream.WriteByte(0x00);
_wsStream.Write(dataBuffer, 0, dataBuffer.Length);
_wsStream.WriteByte(0xff);
读取操作没有返回:
private void Message() // started in different thread
{
while (_readyState == WsState.Open)
{
string data = Receive(); // does _wsStream.ReadByte(); and stops on it forever
var handler = OnMessage;
if (null != handler && data != null)
handler(this, data);
}
}
你能帮我解决命令语法和故障排除的问题吗?
谢谢,
Alex