unable to connect websocket(wss) from c# - javascript

In my application I am connecting chrome extension with windows application using websocket,
Javascript code :
var socket = new WebSocket('ws://172.xx.xxx.xx:11223/');
socket.onopen = function(event)
{
// Web Socket is connected, send data using send()
socket.send("hi..");
};
And C# code :
public static TcpListener Weblistener = null;
public static int selWebSocketPort = 0;
public static void StartListeningSahi()
{
Weblistener = new TcpListener(IPAddress.Parse(ipAddStr), portNumForSelenium);
try{
Weblistener.Start();
int TestingCycle = 100;
// Start listening for connections.
while (TestingCycle > 0){
TcpClient handler = Weblistener.AcceptTcpClient();
// An incoming connection needs to be processed.
lock (ClientSockets.SyncRoot){
if (handler != null){
int i = ClientSockets.Add(new ClientHandler(handler));
((ClientHandler)ClientSockets[i]).Start();
SelWebSocketPort = (handler.Client.RemoteEndPoint as IPEndPoint).Port;
NetworkStream networkStream = handler.GetStream();
Byte[] clientReq = new Byte[handler.Available];
networkStream.Read(clientReq, 0, clientReq.Length);
string headerRequest = Encoding.UTF8.GetString(clientReq);
SendResponseToWebSocket(handler, networkStream, headerRequest);
}
else
continue;
}
}
Weblistener.Stop();
}
catch (Exception e){
Console.WriteLine(e.ToString());
}
}
public static void SendResponseToWebSocket(TcpClient handler, NetworkStream networkStream, string headerRequest)
{
// generate accept key fromm client header request
var key = headerRequest.Replace("ey:", "`")
.Split('`')[1]
.Replace("\r", "").Split('\n')[0]
.Trim();
var responseKey = AcceptKey(ref key);
//create the response for the webclient
var newLine = "\r\n";
var response = "HTTP/1.1 101 Switching Protocols" + newLine
+ "Upgrade: websocket" + newLine
+ "Connection: Upgrade" + newLine
+ "Sec-WebSocket-Accept: " + responseKey + newLine + newLine;
//send respose to the webclient
Byte[] sendBytes = Encoding.ASCII.GetBytes(response);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
selWebSocketPort = (handler.Client.RemoteEndPoint as IPEndPoint).Port;
}
This is working fine for http site. But after that I changed the this javascript line var socket = new WebSocket('ws://172.xx.xxx.xx:11223/'); to var socket = new WebSocket('wss://172.xx.xxx.xx:11223/'); to support https sites, but unable to do so. I am getting below error on chrome -
WebSocket connection to 'wss://172.16.106.22:11223/' failed: WebSocket opening handshake timed out
The handshaking is getting failed as in the request header I am getting some junk value.
Am I missing something ?

Related

nodejs not sending websocket to browser

i made a program that connects my java programm who sends data to my nodejs server using sockets and the nodejs server is supposed to send the received data to the browser using socket.io but there is a problem i do receive the data from java but the node server doesnt send it to the browser here is the code
// Create an instance of the Server and waits for a connexion
net.createServer(function(sock) {
// Receives a connection - a socket object is associated to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
// Add a 'data' - "event handler" in this socket instance
sock.on('data', function(data) {
//data was received in the socket and converting it into string
var textChunk = data.toString('utf8');
io.emit('message', textChunk); //socket.io is supposed to send the data to the browser
console.log(textChunk);
});
// Add a 'close' - "event handler" in this socket instance
sock.on('close', function(data) {
// closed connection
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
}).listen(PORT, HOST);
You may connect Java side (WebSocketServer) to Javascript side (browser) using github.com/TooTallNate/Java-WebSocket.
Java side:
final class Gateway extends WebSocketServer {
private WebSocket _webSocket;
Gateway( IDataManager dataManager, IConfiguration config) {
super( new InetSocketAddress( <host>, <port> );
new Thread( this ).start();
}
#Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
final String request = handshake.getResourceDescriptor();
final String[] req = request.split( "[/=]" );
System.out.printf( "request: %s\n", Arrays.toString( req ));
_webSocket = conn;
...
}
public void publish( ... ) {
final ByteBuffer buffer = ByteBuffer.allocate( ... );
buffer.order( ByteOrder.BIG_ENDIAN );
buffer.putXXX( ... );
buffer.flip();
_webSocket.send( buffer );
}
#Override
public void onMessage( WebSocket conn, String buffer ) {
System.out.printf( "%s\n", buffer );
}
#Override
public void onMessage( WebSocket conn, ByteBuffer buffer ) {
try {
System.out.printf( "%d bytes received from %s",
buffer.remaining(), conn.getRemoteSocketAddress());
if( buffer.position() == buffer.limit()) {
buffer.flip();
}
buffer.order( ByteOrder.BIG_ENDIAN );
final byte xxx = buffer.getXxx();
...
}
catch( final Throwable t ) {
t.printStackTrace();
}
}
#Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
}
#Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
System.out.printf( "code: %d, reason: %s, remote: %s\n", code, reason, remote ? "true" : "false" );
}
}
Javascript side:
var webSocket = new WebSocket(
'ws://' + smoc.PROTOCOL_HOST +
':' + smoc.PROTOCOL_PORT +
'/viewID=' + $scope.viewID );
$scope.webSocket.binaryType = "arraybuffer";
$scope.webSocket.onmessage = function( evt ) {
...
};

How to send/read java ByteBuffer (websocket) from javascript client onmessage function

Server code in java:
#OnMessage
public void onMessage(Session session, ByteBuffer message) {
if (session.isOpen()) {
String msg = new String(message.array());
System.out.println("Message from " + session.getId() + ": " + msg);
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap("I have got the message".getBytes()));
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
} else {
System.out.println("Session is not open");
}
}
Client code in Javascript:
webSocket = new WebSocket("ws://192.168.10.1:2525/myChat/chat");
webSocket.binaryType = 'arraybuffer';
webSocket.onopen = function(event) {
updateOutput("Connected!");
connectBtn.disabled = true;
sendBtn.disabled = false;
};
webSocket.onmessage = function(event) {
updateOutput(event.data);
};
Note:
Server code works fine when I use it with Web GL client as it is send Binary data.
Javascript client works fine when I read String data in Server end
(from java code):
#OnMessage
public void onMessage(Session session, String message) {}
Thanks in advice for any comments.
I've found the solution to the issue.
I have used ByteBuffer.js library to send/read data of ByteBuffer type in JavaScript:
webSocket.binaryType = "arraybuffer";
In the function onmessage for reading data:
var d = event.data;
console.log(d.toString());
In the function send for sending data:
var bb = dcodeIO.ByteBuffer.wrap(text);
webSocket.send(bb.toArrayBiffer());

C# Httpwebrequest detection

What ways are there for a website to detect automated connections made through C# Httpwebrequest?
Such as c#'s default user-agent? Operating System? or what..
have this problem with any other language, just C#?
I'm being blocked from accessing a certain website using Httpwebrequest, I don't
Also it's definitely not my IP address & nor are there any faults in my code as I've tested connections to other websites which work just fine.. Also I stated above I can make connections to the website using C++, C, Vb.net, Java, Python & so on, there is also no difference in header information either.
EDIT:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://services.runescape.com/m=hiscore_oldschool/overall.ws");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "user1=Zezima&submit=Search";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
private const string Url = "http://services.runescape.com/m=hiscore_oldschool/overall.ws";
private static HttpWebRequest BuildWebRequest()
{
var request = WebRequest.Create(Url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 40000;
request.ServicePoint.Expect100Continue = true;
string body = "user1=Zezima&submit=Search";
byte[] bytes = Encoding.Default.GetBytes(body);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
return request;
}
static void Main(string[] args)
{
try
{
HttpWebRequest request = BuildWebRequest();
var response = request.GetResponse() as HttpWebResponse;
var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.Write("Success - " + response.StatusCode);
}
catch (Exception e)
{
Console.Write(e);
}
}
I can take the response from the website. It is not empty.

Why is this node.js tcp server not writing back to Java client until it closes?

Here is an example of a tcp server written in node.js I found:
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
sock.write('You said "' + data + '"');
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
I am trying to use this as a basis for a tcp server which will have to handle multiple incoming connections at the same time. Here is a Java program I wrote to test this:
public static final String MESSAGE = "Hellow world";
public static Semaphore networkLock;
public static void main(String[] args)
{
//writeMessage(MESSAGE);
Thread[] threadPool = new Thread[10];
networkLock = new Semaphore(1);
for (int i = 0; i < threadPool.length; i++)
{
threadPool[i] = new Thread(new Runnable() {
#Override
public void run() {
writeMessage(MESSAGE);
}
});
threadPool[i].start();
}
}
public static void writeMessage(String test)
{
try {
if(sock == null || sock.isClosed())
sock = new Socket(HOST, PORT);
DataOutputStream out =
new DataOutputStream(sock.getOutputStream());
System.out.println("Writting message");
//networkLock.acquire();
out.writeUTF(test);
//networkLock.release();
BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
System.out.println("Waiting for reply");
String input = in.readLine();
System.out.println(input);
// in.close();
// out.close();
// sock.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I start the client, the only output I get from the client is a "Writting message" and "Waiting for reply" a bunch of times. When I shut down the server, I finally get the responses of You said " Hellow world" along with a null or two thrown in usually. As for the server, it prints out the two print statements just fine. Do you think someone could help me out here?
The Java client is using in.readLine() which looks for a newline character in the input stream. However, the server is not writing a newline to the client socket.
So change this:
sock.write('You said "' + data + '"');
to this:
sock.write('You said "' + data + '"\n');

doGET in Servlet does not write in the html page

This is my javascript part
<script language=javascript type="text/javascript">
function myFunction() {
var request = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/Test/Servlet");
request.send();
//document.write("Request GET enviado!");
}
</script>
This is my doGEt part
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Request GET recebido!");
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/Tests";
// Database credentials
String USER = "fabio";
String PASS = "hacking";
Connection conn = null;
Statement stmt = null;
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM people";
ResultSet rs = stmt.executeQuery(sql);
out.println("<html><body>");
// Extract data from result set
while (rs.next()) {
//Retrieve by column name
int person_id = rs.getInt("person_id");
String first_name = rs.getString("first_name");
String last_name = rs.getString("last_name");
//Display values
out.println("Person ID: " + person_id + " | ");
out.println("First name: " + first_name + " | ");
out.println("Last name: " + last_name + "<br>");
}
out.println("</body></html>");
// Clean-up environment
out.close();
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
They work until the point that data is retrieved from DB. The part that does not work is posting the out.println back to HTML page. Could someone please advise?
Thanks,
It is not obvious for me from the question if you did anything with the response like this:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var respdiv = document.getElementById("respdiv");
respdiv.innerHTML = "Response=" + xhr.responseText;
}
xhr.open("GET", "http://localhost:8080/Test/Servlet", true);
xhr.send(null);
Also it was interesting that running in built in eclipse browser it responded with "hello" instead of "SOMETHING" (did not check why) but worked when opened in chrome.
doGet code:
PrintWriter out = response.getWriter();
out.println("SOMETHING");
out.flush();
out.close();

Categories