I have created a socket server using PHP, the code is like this
PHP
function listen()
{
// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : " . $input."\n";
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
listen();
}
set_time_limit(0);
listen();
Taken from http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP
And I create the client socket using Javascript, like this
Javascript
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:25003");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
Then I run the PHP server, it's work, it's listening.
And the I run the Javascript client, it's work, the PHP Server is receiving request from Javascript.
BUt the response from PHP is like this
I don't understand how to change the client message, let's say I want to send message just like "Hello",
1. How can I call it from javascript so the PHP server is receive only "Hello" ?
2. Anyone can explain to me what is the function of each url like this ?
ws://localhost:25003/daemon.php
what is the second parameter? is this connect to my php file? because I try to locate to my php it doesn't work.
PHP Socket server is OK, the problem is Javascript, it's sending a HTTP request and this send is a protocol for HTTP.
You can start the PHP Web Server on that port and answer that petisions whin Ajax queries.
Command line to start php like a Web Server
php -S 127.0.0.1:25003
The document root for WebServer is the same for PHP
Related
I have been advised that the solution in another SO post of mine might involve WebSocket. It just closes the connection instantly when used with my Url, but the javascript.info Url works fine. But why is that?
console.log says:
WebSocket connection to 'wss://verlager.com/hello' failed:
function sentry() {
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser!");
// Let us open a web socket
// THIS WORKS:
let socket = new WebSocket("wss://javascript.info/article/websocket/demo/hello");
// But my server doesn't work! Why doesn't it work on my server?
var ws = new WebSocket("wss://verlager.com/hello");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
console.log("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
console.log("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
console.log("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
console.log("WebSocket NOT supported by your Browser!");
}
}
sentry();
First, I've encountered an error with the exact same format, when I tried to connect to wss://localhost, which wasn't running.
Try specifying the port of your server, I'm not sure which one it assumes by default. Also make sure that your server is running secure websockets and it's dealing correctly with your path /hello.
I have a PHP websocket (Ratchet 13) and it works fine. I can connect to this ws via C# without any problem.
Now, i would like to connect to my websocket but with javascript, and in client side.
On my website, i would like the client to be connected to my websocket, and can send/received real-time data from the server.
Actually the connection success, but events are never called.
EDIT: After few mins the page is loaded, i have this in the console:
"WebSocket connection to 'ws://x:8080/' failed: WebSocket opening handshake timed out"
I have tried a lot of methods.
document.getElementById("value_ws").innerHTML = "coning";
//just some cheks 1
var ws = new WebSocket("ws://localhost:8080");
//here i replace localhost by my IP otherwise it don't connect
ws.onopen = function(e) {
console.log("open");
};
ws.addEventListener('open', function (event) {
ws.send('Hello Server!');
});
//both of theses events are never called
//i successfully receive the connection on my server ws console
//but when i send data, the event is never called
document.getElementById("value_ws").innerHTML = "coned";
//just some cheks 2
If you have some tips you can give me, i take!
Best regards
SOLVED:
problem was coming from my server that wasn't answering the handshake.
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
Some browsers won't let you connect to unsecured websockets. You would need to test with SSL/TLS enabled and "wss://localhost:8080" as your connection.
We had created WCF web service with one method. Service is hosted on external server i.e. Windows Server 2012 and IIS 8.0.
WCF Service URL: http://184.106.9.214/WCFReportingService/Service1.svc
WCF method:
public void ProcessReport()
{
for (int i = 1; i <= 100; i++)
{
// some logic to process the report
Thread.Sleep(100);
// Get the callback channel to send messages to the client
OperationContext.Current.
GetCallbackChannel<IReportServiceCallback>().Progress(i);
}
}
We are trying to create client using HTML5 and JavaScript. Below is the logic we used to initiate the connection.
ws = new WebSocket("ws://localhost/WCFReportService/Service1.svc");
alert(ws);
ws.onopen = function () {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
$("#spanStatus").text("connected");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
$("#spanStatus").text(evt.data);
};
ws.onerror = function (evt) {
$("#spanStatus").text(evt.message);
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
$("#spanStatus").text("disconnected");
};
We were not able to establish the connection to server. We are thinking that it might be something to do with client side web.config file. But we are not sure how to implement or build connection.
Can anyone help us to build client-server connection?
Thanks.
It might help someone with similar problem I had. Below are the links I used and I was able to get it working.
Introduction 2 : http://www.codeproject.com/Articles/618032/Using-WebSocket-in-NET-4-5-Part-2
Introduction 3 : http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-4-5-Part-3
I'm use example from Google Team to create a TCP Server using Chrome App Extension API. Sample is work correctly and I connect via telnet and send commands.
When I'm trying to connect to this server from client and try send data. Client connected to server and send data, but server not receive data. Client on PHP, for test I'm using this example.
What I doing wrong?:(
Thx.
Solve: I'm resolve problem. In php script, after connect need delay. I'm using usleep function. All worked
Worked Example:
$fp = pfsockopen("ip", port, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "minimize";
usleep(125000);
$r = fputs($fp, $out);
sleep(1); //
$out = "restore";
$r = fputs($fp, $out);
usleep(125000);
fclose($fp);
}
I am writing a very simple chat application based on the HTML5 WebSocket technology where the server (implemented using node.js WS) keeps track of all the connected users and broadcasts each received message. The client on the other hand, connects to the server and according to user's actions, sends messages to the server.
The problem that I am observing is that unless the server sends a message to the client after opening the connection, all messages sent from the client running on Google Chrome get buffered until several messages have been sent. Once the buffer is full, all messages are sent at once. This creates a very unresponsive chat experience for the end user.
The fix that I found was to add single ws.send("Hello Client:" + clientId); after opening the connection on the server side, but I am not sure why this is necessary? Below you can find snippet from my client and server components, but the entire source code is available at ChatMate git project.
Server Code:
wsServer.on('connection', function (ws) {
var clientId = nextClientId += 1;
clients[clientId] = ws;
log("Accepted connection from client " + clientId + ".");
//The fix: If you emit this initial message from the server, then
//all of client's messages will be cached.
ws.send("Hello Client: " + clientId);
ws.on('message', function (message) {
log("Received message: " + message);
var id;
for (id in clients ) {
if (clients.hasOwnProperty(id)) {
if (parseInt(id, 10) !== clientId) {
clients[id].send(message);
}
}
}
});
});
Client Code:
function WebSocketTest() {
"use strict";
ws = new WebSocket("ws://DOMAIN:8080/");
ws.onopen = function () {
console.log("Connection is open.");
//This message will not be sent if the server does not send
//a message first.
ws.send("Client Message.");
};
ws.onmessage = function (e) {
console.log("Message is received: " + e.data);
};
}
Thanks!