Jump to content

sagnik

Members
  • Posts

    484
  • Joined

  • Last visited

  • Days Won

    1

Posts posted by sagnik

  1. Hi again, I'm creating a chat system with PHP. So I've created the WebSocket server in PHP and the client using the built-in browser WebSocket API. Everything is working fine when I access the client using 'http' & 'ws' protocol, but my problem is when I access the client using 'https' & 'wss', I'm getting the error in firefox saying that: "Firefox can’t establish a connection to the server at wss://192.168.1.201:9000/server.php.". The files are located on https://192.168.1.201/socket/chat2/.

     

    Here are the codes:

     

     

    /socket/chat2/server.php:

    <?php
    $host = '192.168.1.201'; //host
    $port = '9000'; //port
    $null = NULL; //null var
    
    //Create TCP/IP sream socket
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    }
    //reuseable port
    socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
    
    //bind socket to specified host
    socket_bind($socket, 0, $port);
    
    //listen to port
    socket_listen($socket);
    
    //create & add listning socket to the list
    $clients = array($socket);
    
    //start endless loop, so that our script doesn't stop
    while (true) {
    	//manage multipal connections
    	$changed = $clients;
    	//returns the socket resources in $changed array
    	socket_select($changed, $null, $null, 0, 10);
    	
    	//check for new socket
    	if (in_array($socket, $changed)) {
    		$socket_new = socket_accept($socket); //accpet new socket
    		$clients[] = $socket_new; //add socket to client array
    		
    		$header = socket_read($socket_new, 1024); //read data sent by the socket
    		perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
    		
    		socket_getpeername($socket_new, $ip); //get ip address of connected socket
    		$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
    		send_message($response); //notify all users about new connection
    		
    		//make room for new socket
    		$found_socket = array_search($socket, $changed);
    		unset($changed[$found_socket]);
    	}
    	
    	//loop through all connected sockets
    	foreach ($changed as $changed_socket) {	
    		
    		//check for any incomming data
    		while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
    		{
    			$received_text = unmask($buf); //unmask data
    			$tst_msg = json_decode($received_text, true); //json decode 
    			$user_name = $tst_msg['name']; //sender name
    			$user_message = $tst_msg['message']; //message text
    			$user_color = $tst_msg['color']; //color
    			
    			//prepare data to be sent to client
    			if(!empty($tst_msg['notification']))
    				$response_text = array('type'=>'notification', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color);
    			else
    				$response_text = array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color);
    			
    			$response_text = mask(json_encode($response_text));
    			send_message($response_text); //send data
    			break 2; //exist this loop
    		}
    		
    		$buf = @socket_read($changed_socket, 1024, PHP_NORMAL_READ);
    		if ($buf === false) { // check disconnected client
    			// remove client for $clients array
    			$found_socket = array_search($changed_socket, $clients);
    			socket_getpeername($changed_socket, $ip);
    			unset($clients[$found_socket]);
    			
    			//notify all users about disconnected connection
    			$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
    			send_message($response);
    		}
    	}
    }
    // close the listening socket
    socket_close($socket);
    
    function send_message($msg)
    {
    	global $clients;
    	foreach($clients as $changed_socket)
    	{
    		@socket_write($changed_socket,$msg,strlen($msg));
    	}
    	return true;
    }
    
    
    //Unmask incoming framed message
    function unmask($text) {
    	$length = ord($text[1]) & 127;
    	if($length == 126) {
    		$masks = substr($text, 4, 4);
    		$data = substr($text, 8);
    	}
    	elseif($length == 127) {
    		$masks = substr($text, 10, 4);
    		$data = substr($text, 14);
    	}
    	else {
    		$masks = substr($text, 2, 4);
    		$data = substr($text, 6);
    	}
    	$text = "";
    	for ($i = 0; $i < strlen($data); ++$i) {
    		$text .= $data[$i] ^ $masks[$i%4];
    	}
    	return $text;
    }
    
    //Encode message for transfer to client.
    function mask($text)
    {
    	$b1 = 0x80 | (0x1 & 0x0f);
    	$length = strlen($text);
    	
    	if($length <= 125)
    		$header = pack('CC', $b1, $length);
    	elseif($length > 125 && $length < 65536)
    		$header = pack('CCn', $b1, 126, $length);
    	elseif($length >= 65536)
    		$header = pack('CCNN', $b1, 127, $length);
    	return $header.$text;
    }
    
    //handshake new client.
    function perform_handshaking($receved_header,$client_conn, $host, $port)
    {
    	$headers = array();
    	$lines = preg_split("/\r\n/", $receved_header);
    	foreach($lines as $line)
    	{
    		$line = chop($line);
    		if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
    		{
    			$headers[$matches[1]] = $matches[2];
    		}
    	}
    
    	$secKey = $headers['Sec-WebSocket-Key'];
    	$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    	//hand shaking header
    	$upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
    	"Upgrade: websocket\r\n" .
    	"Connection: Upgrade\r\n" .
    	"WebSocket-Origin: $host\r\n" .
    	"WebSocket-Location: wss://$host:$port/server.php\r\n".
    	"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    	socket_write($client_conn,$upgrade,strlen($upgrade));
    }
    ?>
    

    /socket/chat2/client.js:

    var colors = [
    	'#007AFF','#FF7000','#FF7000','#15E25F','#CFC700','#CFC700','#CF1100','#CF00BE','#F00'
    ];
    var color_pick = Math.floor(Math.random() * colors.length);
    
    //create a new WebSocket object.
    var msgBox = $('#message-box');
    var wsUri = "wss://192.168.1.201:9000/server.php";
    websocket = new WebSocket(wsUri);
    
    websocket.readyStateChange = function (e) { // connection is open 
    	console.log(e);
    }
    
    websocket.onopen = function (ev) { // connection is open 
    	msgBox.append('<div class="system_msg" style="color:#bbbbbb">Welcome to my "Demo WebSocket Chat box"!</div>'); //notify user
    }
    // Message received from server
    websocket.onmessage = function (ev) {
    	var response = JSON.parse(ev.data); //PHP sends Json data
    
    	
    	
    	var res_type = response.type; //message type
    	var user_message = response.message; //message text
    	var user_name = response.name; //user name
    	var user_color = response.color; //color
    
    console.log(res_type);
    	switch (res_type) {
    		case 'usermsg':
    			if($("#user_typing").length > 0)
    				$("#user_typing").remove();
    			msgBox.append('<div><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="user_msg">' + user_message + '</span></div>');
    			break;
    		case 'system':
    			msgBox.append('<div style="color:#bbbbbb">' + user_message + '</div>');
    			break;
    		case 'notification':
    			var user_notification = response.notification; //notification type
    			if(user_notification === 'typing'){
    				if($("#user_typing").length <= 0)
    					msgBox.append('<div id="user_typing"><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="system_msg">' + user_message + '</span></div>');
    			} else
    				msgBox.append('<div id="user_notification"><span class="user_name" style="color:' + user_color + '">' + user_name + '</span> : <span class="system_msg">' + user_message + '</span></div>');
    			break;
    	}
    	msgBox[0].scrollTop = msgBox[0].scrollHeight; //scroll message 
    
    };
    
    websocket.onerror = function (e) {
    	msgBox.append('<div class="system_error">Error Occurred - ' + e.data + '</div>');
    };
    websocket.onclose = function (e) {
    	if(e.wasClean)
    		msgBox.append('<div class="system_msg">Connection Closed</div>');
    	else
    		msgBox.append('<div class="system_error">Connection Interrupted - [Error#' + e.code + '] ' + e.reason + '</div>');
    };
    
    //Message send button
    $('#send-message').click(function () {
    	send_message();
    });
    
    //User hits enter key 
    $("#message").on("keydown", function (event) {
    	if (event.which == 13) {
    		send_message();
    	}
    });
    //User typing
    $("#message").on("keypress", function (event) {
    	if (event.which !== 13)
    		send_notification('typing','Typing...');
    });
    
    var notifications = [], isTyping = false;
    
    //Send message
    function send_message() {
    	var message_input = $('#message'); //user message text
    	var name_input = $('#name'); //user name
    
    	if (message_input.val() == "") { //empty name?
    		alert("Enter your Name please!");
    		return;
    	}
    	if (message_input.val() == "") { //emtpy message?
    		alert("Enter Some message Please!");
    		return;
    	}
    	
    	isTyping = false;
    
    	//prepare json data
    	var msg = {
    		message: message_input.val(),
    		name: name_input.val(),
    		color: colors[color_pick]
    	};
    	//convert and send data to server
    	websocket.send(JSON.stringify(msg));
    	message_input.val(''); //reset message input
    }
    
    //Send message
    function send_notification(type, msg) {
    	var name_input = $('#name'); //user name
    	notifications.push(type);
    	//prepare json data
    	var msg = {
    		notification: type,
    		message: msg,
    		name: name_input.val(),
    		color: colors[color_pick]
    	};
    	if(!isTyping){
    		isTyping = true;
    		//convert and send data to server
    		websocket.send(JSON.stringify(msg));
    	}
    }
    

    /socket/chat2/index.html:

    <?php 
    $colors = array('#007AFF','#FF7000','#FF7000','#15E25F','#CFC700','#CFC700','#CF1100','#CF00BE','#F00');
    $color_pick = array_rand($colors);
    ?>
    <!DOCTYPE html>
    <html>
    	<head>
    		<meta name="viewport" content="width=device-width, initial-scale=1">
    		<style type="text/css">
    			.chat-wrapper {
    				font: bold 11px/normal 'lucida grande', tahoma, verdana, arial, sans-serif;
    				background: #00a6bb;
    				padding: 20px;
    				margin: 20px auto;
    				box-shadow: 2px 2px 2px 0px #00000017;
    				max-width:700px;
    				min-width:500px;
    			}
    			.system_error {
    				color: #a00;
    			}
    			.system_msg {
    				color: #bbb;
    			}
    			.user_msg {
    				color: #00f;
    			}
    			#message-box {
    				width: 97%;
    				display: inline-block;
    				height: 300px;
    				background: #fff;
    				box-shadow: inset 0px 0px 2px #00000017;
    				overflow: auto;
    				padding: 10px;
    			}
    			.user-panel{
    				margin-top: 10px;
    			}
    			input[type=text]{
    				border: none;
    				padding: 5px 5px;
    				box-shadow: 2px 2px 2px #0000001c;
    			}
    			input[type=text]#name{
    				width:20%;
    			}
    			input[type=text]#message{
    				width:60%;
    			}
    			button#send-message {
    				border: none;
    				padding: 5px 15px;
    				background: #11e0fb;
    				box-shadow: 2px 2px 2px #0000001c;
    			}
    		</style>
    	</head>
    	<body>
    		<div class="chat-wrapper">
    			<div id="message-box"></div>
    			<div class="user-panel">
    				<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />
    				<input type="text" name="message" id="message" placeholder="Type your message here..." maxlength="100" />
    				<button id="send-message">Send</button>
    			</div>
    		</div>
    		<script src="https://cdn.sgnetworks.net/jquery/lib/3.2.1/jquery-3.2.1.min.js"></script>
    		<script language="javascript" type="text/javascript" src="client.js"></script>
    	</body>
    </html>
    
  2. Okay, thanks. I hope Krydos sir will do something to allow users to park those domains. In case it takes too long, can you suggest me some other free domain providers (any type of domain would be good, except Freenom).

    Meanwhile, can you look at my another topic which is still not solved: https://www.helionet.org/index/topic/38541-development-of-an-apache-httpd-handler-module/?fromsearch=1

  3. Okay after trying that, I'm getting the following error in cPanel which is as same as the eu.org:

    There was an error when the system attempted to create the alias. Park::park failed: (XID 5un3s3) Sorry, the domain is already pointed to an IP address that does not appear to use DNS servers associated with this server. Please transfer the domain to this servers nameservers or have your administrator add one of its nameservers to /etc/ips.remotedns and make the proper A entries on that remote nameserver.

  4. And one more thing, when I'm trying to add the domain in cPanel, I'm getting the following error:

    There was an error when the system attempted to create the alias. Park::park failed: (XID ukhkns) Sorry, the domain is already pointed to an IP address that does not appear to use DNS servers associated with this server. Please transfer the domain to this servers nameservers or have your administrator add one of its nameservers to /etc/ips.remotedns and make the proper A entries on that remote nameserver.

  5. Okay, I got it, But the problem is, I need two domains if I can't setup eu.org domains then where I can get a new domain, and I don't want to spend money (as the websites will be under testing). I can't even register domains on Freenom because my account is flagged when I forgot to renew a domain and now the domain is declared as "FRAUD". I can use any type of domains whether it's a TLD/ccTLD/gTLD/2nd-level/3rd-level.

  6. Nothing much to explain. Here is the logs showing when setting DNS records in nic.eu.org:

    Quote

    ---- Servers and domain names check

     

    Warning: ignoring IP 65.19.143.3 for NS1.HELIOHOST.ORG (not in SGTEST.IN.EU.ORG)

    Warning: ignoring IP 64.62.211.133 for NS2.HELIOHOST.ORG (not in SGTEST.IN.EU.ORG)

    Getting IP for NS1.HELIOHOST.ORG: 65.19.143.3

    Getting IP for NS1.HELIOHOST.ORG: 2001:470:1:1ee::1002

    Getting IP for NS2.HELIOHOST.ORG: 64.62.211.133

    Getting IP for NS2.HELIOHOST.ORG: 2001:470:1:1ee::2

     

    ---- Checking SOA records for SGTEST.IN.EU.ORG

     

    SOA from NS1.HELIOHOST.ORG at 65.19.143.3: Error: Answer not authoritative (145.350 ms)

    SOA from NS1.HELIOHOST.ORG at 2001:470:1:1ee::1002: Error: Timeout (20002.261 ms)

    SOA from NS2.HELIOHOST.ORG at 64.62.211.133: Error: Answer not authoritative (149.082 ms)

    SOA from NS2.HELIOHOST.ORG at 2001:470:1:1ee::2: Error: Timeout (20001.727 ms)

     

    ---- Checking NS records for SGTEST.IN.EU.ORG

     

    NS from NS1.HELIOHOST.ORG at 65.19.143.3: Error: Answer not authoritative (148.990 ms)

    NS from NS1.HELIOHOST.ORG at 2001:470:1:1ee::1002: Error: Timeout (20000.864 ms)

    NS from NS2.HELIOHOST.ORG at 64.62.211.133: Error: Answer not authoritative (142.665 ms)

    NS from NS2.HELIOHOST.ORG at 2001:470:1:1ee::2: Error: Timeout (20096.117 ms)

     

     

    8 errors(s)

    2 warning(s)

  7. Hello, everyone! I'm going to start a new project which will be a programming language. The structure of the language will be like PHP & Java. It will be built using any one or more than one of the following languages. It will be an open-source application and run either via Console or Apache Module (later via IDE or Runner Application like Java). Anyone who wants to work with me and has knowledge in the following languages can contact me or comment below to discuss how to start and progress. The application will be built using C/C++ (and obviously the Apache Module). We'll start from a simple language by writing a simple Lexer, Tokenizer & Parser for the interpreter then we'll continue to improve the language constantly. If anyone wants to join me can give a reply to this post or send an email at sagnikganguly2012[at]rediffmail[dot]com along with his/her GitHub Username after that he/she can start contributing to the following repository:

    https://github.com/SGNetworksIndia/SGSP.

  8. Hello Admins, I request you to change the document root of my main domain as I've too many addon-domains it will be better to keep them organized. So kindly give a response telling that if it's possible or not. Because I don't know how the websites are hosted in heliohost but if the websites are configured as VirtualHosts then it might be possible. I know that there are some rules for every request, I don't know if my request complies with the rules of heliohost as I've not seen such a rule there, it's also possible that I might be the first one here who's requesting to change the document root of the main domain.

  9. I understood what you've said. But the task I've been assigned by an IT company for whom I have given an interview for "Full-stack Web Developer" at first round of the telephonic interview. Now the HR Manager wants me to develop the app for my 2nd round of interview. They have allowed me to use any third-party libraries. But I'm not comfortable with any third-party libraries, that's why I've asked for without any framework or libraries.

  10. Hi, I wat to build a scalable web app for login/register API in PHP without using any third-party frameworks or libraries as well as the API URLs for the app will be as follows:

    Signup URL: /user/signup

    Signin URL: /user/signin

    Profile URL: /user/profile

    Update profile URL: /user/profile/update

     

    After login/register the app should generate and return the access token which is required to access profile. How can I do it?

  11. I have the following class:

    SGNBEResponseCode class:

    <?php
    namespace SGNBackend\SGNBEResponseCodes;
    
    class SGNBEResponseCode {
    	public function __construct(){
    		print_r(__CLASS__);
    		return __CLASS__;
    	}
    }
    ?>
    
    <?php
    namespace SGNBackend\SGNBEResponseCodes;
    
    class Common extends SGNBEResponseCode {
    	public const UNKNOWN_ERROR = -1;
    	public const INVALID_REQUEST = 0;
    	public const REQ_FAILED = 100;
    	public const DB_QUERY_ERROR = 101;
    	public const DB_COUNT_ERROR = 102;
    	public const DB_FETCH_ERROR = 103;
    	public const EMPTY_PARAM_VALUE = 104;
    	public const INVALID_PARAM_VALUE = 105;
    	public const REQ_DONE = 106;
    
    	public function __construct(){
    		print_r(__CLASS__);
    		return __CLASS__;
    	}
    }
    ?>
    
    Here SGNBEResponse class:

    <?php
    namespace SGNBackend;
    
    class SGNBEResponse{
    	const response = array("error"=>true, "code"=>-1, "name"=>"UNKNOWN_ERROR", "message"=>"An unknown error has occurred");
    
    	public static function generateErrorFromCode(SGNBEResponseCode $code, string $args = null){
    		$c = debug_backtrace();
    		print_r($c);
    		//return "test";
    	}
    }
    ?>
    
    And I'm trying to access the constants like this:

    <?php
    $sgnbe = new \SGNBackend\SGNBEResponse();
    print_r(\SGNBackend\SGNBEResponse::generateErrorFromCode(\SGNBackend\SGNBEResponseCodes\Common::INVALID_REQUEST));
    ?>
    
    And when I access the constants an instance of the class along with the name of the constant and value should be returned instead of the value of the constants. Can I do it? If yes then how?
×
×
  • Create New...