In laravel how to use multiple threads? to run 2 socket server simultaneously
i want to run 2 socket servers simultaneously. Listening to the connections in laravel. In laravel do we have any package for creating multiple threads?
See also questions close to this topic
-
Python call to PHP - malformed header from script Bad header: Array
Very strange - I've been using a python script that scrapes data and then passes it to a php-script - Worked like charm for weeks, until today something happened.
I got the following message from apache2 errorlog:
malformed header from script 'pytest.py': Bad header: Array
So it seems to be derived from this python script, the php-script is called but there is a server 500 error and the error log tells about a malformed header from python
python script
#!/home/john/mydir/my_venv/bin/python3 # enable debugging import cgitb from bs4 import BeautifulSoup from urllib.request import urlopen, Request import os cgitb.enable() print ("Content-type: text/html\r\n\r\n") url = "https://www.xxxx.." soup = BeautifulSoup(urlopen(url).read()) stockNames = [] stockClose = [] stockHigh = [] stockLow = [] stockTurnover = [] for tag in soup.select('td[data-title="Namn"]'): name = tag.get_text(strip=True, separator='\n') stockNames.append(name) for tag in soup.select('td[data-title="Senast"]'): close = tag.get_text(strip=True, separator='\n') stockClose.append(close) os.system('php /var/www/html/omx/dataparser.php %s %s'%(stockNames, stockClose))
the php script (snippet)
<?php if (isset($argc)) { unset($argv["0"]); // remove first argument i.e. filename ... }
Any Idea whats wrong, why this suddenly happened? Could a packetsniffer be in place to see whats going on?
-
How to have only 3 checkboxes per line with dinamic checkbox number
How to have only 3 checkboxes per line with dinamic checkbox number, for example I have 21 checkboxes (read checkbox name form a database) This is my code
<div class='form-group'> <div class="col-lg-12"> <?php $sql = "SELECT id, posizione, nome FROM user_livelli"; $result = $conn->query($sql); if (!empty($result) && $result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $id = $row['id']; $posizione = $row['posizione']; $nome = $row['nome']; echo "<input type='checkbox' name='nome_posiz[]'>" ." " .$nome ." "; } } ?> </div> </div>
I have the following situation
But I would like to have only 3 checkboxes per line, for example the 3 with black dot on the first line, the 3 with the red dot on another line, the 3 with the green dot on another line and so on. Something like this done using PAINT
-
How can I redirect all users via a single page based on admin rights?
I'm trying to set up a login for website, where a user can have one of three states. I have this set in a connected file called 'authenticate.php' which on login checks my DB for the value "version" where the values can be 1,2 or 3 depending on access level. This file is then set up to redirect set up to one of three different pages, for instance home1.php, home2.php, home3.php. I am happy with having 3 separate pages, as I want this control.
In the same directory as these files, there is a folder of content which users will only be able to see some of the pages from. For example:
- website (FOLDER)
- authenticate.php
- index.html
- home1.php
- home2.php
- home3.php
- content (FOLDER)
- news1.html
- news2.html
- news3.html
The problem is, that with my current implementation, when the user is on any one of these content pages, I can't link them back to the right version of the home page they're meant to be seeing.
As a solution, I was thinking of using a new file 'home.php' to always direct to, and then redirect the user to where they need to go, as opposed to dealing with all of this in the authentication.php file like I'm doing currently. This would allow me to send the user to home.php, and then they'd be redirected to the version they're meant to see.
I have used what's happening in the original authenticate.php and I have tried replicating the check to the DB to get the value of "version", but this doesn't seem to be working. As I'm sure is obvious from my code, I am not experienced in PHP I am also unsure whether it's necessary to reconnect to the DB once this has already been made in the session.
Any help would be really appreciated, as I'm sure there's a better way to do this.
Thank you!
Code:
Authenticate.php
session_start(); $DATABASE_HOST = 'localhost'; $DATABASE_USER = 'john' $DATABASE_PASS = 'password'; $DATABASE_NAME = 'users'; $con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME); if ( mysqli_connect_errno() ) { exit('Failed to connect to MySQL: ' . mysqli_connect_error()); } if ( !isset($_POST['username'], $_POST['password']) ) { exit('Please fill both the username and password fields!'); } if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) { $stmt->bind_param('s', $_POST['username']); $stmt->execute(); $stmt->store_result(); if ($stmt->num_rows > 0) { $stmt->bind_result($id, $password); $stmt->fetch(); if ($_POST['password'] === $password) { session_regenerate_id(); $_SESSION['loggedin'] = TRUE; $_SESSION['name'] = $_POST['username']; $_SESSION['id'] = $id; header('Location: home.php'); } else { echo 'Incorrect username and/or password!'; } } else { echo 'Incorrect username and/or password!'; } $stmt->close(); }
Home.php
<?php session_start(); if (!isset($_SESSION['version'] == 1 )) { header('Location: home1.php'); exit; } if (!isset($_SESSION['version'] == 2 )) { header('Location: home2.php'); exit; } if (!isset($_SESSION['version'] == 3 )) { header('Location:home3.php'); exit; }
- website (FOLDER)
-
laravel spatie database backup to google drive on cpanel
Hi i am using spatie(spatie/laravel-backup) package for database backup. Also using nao-pon/flysystem-google-drive package for google drive upload using laravel schedule command. Here is command code
$schedule->command('database:check')->everyMinute(); $schedule->command('backup:clean')->everyMinute(); $schedule->command('backup:run --only-db')->everyMinute();
When i run php artisan schedule:run on my local then i get a zip file on my google drive.But when i run this on cpanel then i didn't get any file in my google drive. Here is code for cron job
/usr/local/bin/php /home/masumcom/binary.masum3.com/artisan schedule:run
One command run perfectly but other two not working perfectly
$schedule->command('database:check')->everyMinute();
Only this one working perfectly
-
Laravel combine many used @error into a single file
In
Laravel
web application i used many of@error
in view and i would like to combine them into a single view,for example i have
@error('name') <div class="badge d-block mb-1" style="color:#fffb00;"> {{ $message }} </div> @enderror @error('mobile_number') <div class="badge d-block mb-1" style="color:#fffb00;"> {{ $message }} </div> @enderror @error('invited_by') <div class="badge d-block mb-1" style="color:#fffb00;"> {{ $message }} </div> @enderror
and i want to use a single file as view for them:
message.blade.view
file:@error('{{ $field }}') <span class="form-text" style="color:#fffb00;"> <i class="icon-cancel-circle2 mr-2"></i> {{ $message }} </span> @enderror
when i use
@include('livewire.auth.partials.message',['field'=>'name']) @include('livewire.auth.partials.message',['field'=>'mobile_number'])
it doesn't show any error, but i can get
$field
variable intomessage.blade.view
file{{ $field }} @error('{{ $field }}') <span class="form-text" style="color:#fffb00;"> <i class="icon-cancel-circle2 mr-1"></i> {{ $message }} </span> @enderror
-
How to add a Consecutive Number in Angular JS
Every time the customer creates a "Proveedor (provider)", they need to fill the Numero de proveedor field in order to continue as you can see in this picture (the top-left input field):
The problem is that the DB has around 1000+ providers, and the "Numero de proveedor" was randomly selected (I've providers with 1234567890 number) so, I want to see how can I set the consecutive number not being used already in that field when the user access to that view.
What I want is to access to the create view of Proveedores and see that field filled automatically with a number not being used.
This is my code:
<div class="form-group col-md-4"> <label for="razon_social">Numero de proveedor</label> <input ng-model="proveedor.codigo_empresa" class="form-control" type="number" placeholder="Codigo empresa"> </div>
If the solution can be in AngularJS it would be great!
Thanks for the help.
-
Should I resend or reconnect if the acknowledgement for a sent message is missing?
In a distributed system, to ensure the peer has received a message correctly, we may use application level acknowledgement mechanism (ACK).
But when the client and the server is connecting via TCP or WebSocket, if the application level ACK for a sent message is not received by the sender, does it mean the connection is broken and should be reconnected?
Is it possible for the data or application level ACK is missing from application level but actually successfully transmitted in TCP level? (In this case, resending the message may be economical.)
-
Receiving image through sockets on androidstudio
I have written a code on Android Studio to receive images from a socket server and the application connects to the server every time a button is clicked.
However, when I run the app and click the button nothing shows up but the server sends a message saying the photo is sent. When I click the button again, for the second time (the server is not connected) the image pops up instantly.
I think the issue is that the thread isn't shutting down completely when I click the button once but if I click it again, the thread shuts down forcefully and starts a new one so the image is shown.
The code for the main activity java file is :
package com.example.myapplication; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.Socket; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTextViewReplyFromServer; private EditText mEditTextSendMessage; private ImageView mImg; private byte [] imgbyte; Handler updateConversationHandler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button buttonSend = (Button) findViewById(R.id.btn_send); mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message); mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server); mImg = (ImageView)findViewById(R.id.imageView); String filepath = "/sdcard/DCIM/img.jpeg"; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_send: Thread fst = new Thread(new ServerThread()); fst.start(); break; } } public class ServerThread implements Runnable { byte [] line; Bitmap bitmap; public void run() { try { Socket client = new Socket("192.168.1.145", 5560); while (true) { // LISTEN FOR INCOMING CLIENTS try { int bytesRead; int current = 0; int filesize=215320; byte [] mybytearray2 = new byte [filesize]; InputStream is = client.getInputStream(); FileOutputStream fos = new FileOutputStream("/sdcard/DCIM/img.jpg"); // destination path and name of file //FileOutputStream fos = new FileOutputStream("/storage/sdcard0/Pictures/Screenshots/"); BufferedOutputStream bos = new BufferedOutputStream(fos); bytesRead = is.read(mybytearray2,0,mybytearray2.length); current = bytesRead; do { bytesRead = is.read(mybytearray2, current, (mybytearray2.length-current)); if(bytesRead >= 0) current += bytesRead; } while(bytesRead > -1); bos.write(mybytearray2, 0 , current); bos.flush(); // bitmap = BitmapFactory.decodeByteArray(mybytearray2 , 0, mybytearray2.length); // mImg.setImageBitmap(bitmap); //System.out.println(end-start); updateConversationHandler.post(new updateUIThread(mybytearray2)); bos.close(); client.close(); break; } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } } class updateUIThread implements Runnable { private byte[] byteArray;//private String msg; public updateUIThread(byte[] array){ //public updateUIThread(String str) { this.byteArray=array; //this.msg = str; } @Override public void run() { Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length); mImg.setImageBitmap(bitmap);//text.setText(text.getText().toString()+"Client Says: "+ msg + "\n"); } } }
Is there anyway I can kill the thread immediately after the image is recieved?
My image also shows up on the android emulator but does not show up on my phone. What could be the reason for this?
Edit : if i start the thread on the oncreate section, the image pops up as soon as the application is started
Edit : python server code :
import socket from time import sleep from time import time host = '' port = 5560 filePath = "/media/pi/ESD-USB/image.jpg" def setupServer(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket created.") try: s.bind((host, port)) except socket.error as msg: print(msg) print("Socket bind comlete.") return s def setupConnection(): s.listen(1) # Allows one connection at a time. conn, address = s.accept() print("Connected to: " + address[0] + ":" + str(address[1])) return conn def sendPic(s, filePath): print(filePath) pic = open(filePath, 'rb') chunk = pic.read() size = len(chunk) print (size) t = time() print("Sending Picture") s.sendall(chunk) pic.close() print("Done sending") print("Elapsed time = " + str(time() - t) + 's') s.close() return "Done sending" def backup(filePath): conn = setupConnection() response = sendPic(conn, filePath) return response s = setupServer() while True: print(filePath) backup(filePath) print("Everything should be backed up now.") break
-
Realtime One to one chat after selecting user from user list in node js and socket io
I am using node and socket io, where user can select a user and start one to one chat. Of any history is exists then load. Using this code message every thing is working with the problem is when user sends message it emits to every user. i have tried soket io.to('') but nothing works. please help me in this. Thank you in advance,
io.on('connection', (socket) => { sok_connections.push(socket); init chat when user click on user then create chat room or if room exist then set socket socket.on('chat-start', function (data) { var sql = "SELECT * FROM chat_rooms WHERE user_1 ='" + data.sender_id + "' AND user_2='" + data.reciver_id + "' OR user_2 ='" + data.sender_id + "' AND user_1='" + data.reciver_id + "'"; pool.getConnection(function (err, connection) { connection.query(sql, function (ch_err, ch_result, ch_fields) { if (ch_err) throw ch_err; if (ch_result.length == 0) { create chat room var query = "INSERT INTO `chat_rooms`(`chat_uid`, `user_1`, `user_2`) VALUES ('" + uniqid('CHAT-ROOM-', '-ESS') + "','" + data.sender_id + "','" + data.reciver_id + "')"; connection.query(query, function (c_ch_err, c_ch_result, c_ch_fields) { if (c_ch_err) throw c_ch_err; var get_data = "select * from chat_rooms where '" + c_ch_result.insertId + "' "; connection.query(get_data, function (s_ch_err, s_ch_result, s_ch_fields) { if (s_ch_err) throw err; current_chat_room_dets.sender_id = data.sender_id; current_chat_room_dets.reciver_id = data.reciver_id; current_chat_room_dets.chat_uid = s_ch_result[0].chat_uid; socket.join(current_chat_room_dets.chat_uid); }); }); } else { var old_chats = "SELECT * FROM conversations WHERE chat_uid='" + ch_result[0].chat_uid + "'"; connection.query(old_chats, function (co_err, co_result, co_fields) { if (co_err) throw co_err; current_chat_room_dets.sender_id = data.sender_id; current_chat_room_dets.reciver_id = data.reciver_id; current_chat_room_dets.chat_uid = ch_result[0].chat_uid; socket.join(current_chat_room_dets.chat_uid); }); } }); }); }); when user change user on chat room socket.on('unsubscribe', function () { socket.leave(current_chat_room_dets.chat_uid); }) load old message and pushing to messsages socket.on('initial-messages', function (data) { var sql = "SELECT * FROM conversations WHERE chat_uid='" + current_chat_room_dets.chat_uid + "'"; pool.getConnection(function (err, connection) { connection.query(sql, function (err, result, fields) { if (err) throw err; connection.release(); for (let res of result) { io.to(current_chat_room_dets.chat_uid).emit('messages', res); } }); }); }); when new user comes set status of user and add to user list socket.on('new user', function (data) { var sql = "SELECT * FROM users"; pool.getConnection(function (err, connection) { connection.query(sql, function (err, result, fields) { connection.release(); if (err) throw err; for (let au of result) { if (au.id == data.user_id) { au.active = true } else { au.active = false } } io.sockets.emit('users', result); }); }); }); when user send a message then post message socket.on('new-message', function (message) { var query = "INSERT INTO `conversations` (`chat_uid`,`message`,`sender`) VALUES ('" + current_chat_room_dets.chat_uid + "','" + message.message + "','" + current_chat_room_dets.sender_id + "')"; pool.getConnection(function (err, connection) { connection.query(query, function (err, rows) { if (err) throw err; }); connection.release(); io.to(current_chat_room_dets.chat_uid).emit('messages', message); }); }); get user typing status socket.on("typing", function (data) { io.log(data, "typing"); socket.broadcast.emit("typing", data); }); socket.once("disconnect", function (data) { console.log(socket.userId, "disconnected"); }); });