Answer the question
In order to leave comments, you need to log in
Chat on socket. Logic for sending messages?
Good day, gentlemen.
Recently I came across such an interesting thing as sockets and decided to write a chat to better understand this issue.
What happened: I
wrote a server that creates a socket, gets ip, listens / binds connections.
Wrote a client that connects to the server.
Server:
set_time_limit(0);
$address = "127.0.0.1";
$port = 1000;
try {
echo 'Create socket ... ';
$socket_desc = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//Создаем сокет.Получаем дескриптор для соединения.
if (!$socket_desc) {
throw new Exception('Ошибка создания сокета'.socket_last_error());
}
echo "Bind socket....";
if(!socket_bind($socket_desc,$address,$port)){//Привязываем полученный дескриптор к ip ресурс.
throw new Exception('Ошибка привязки сокета'.socket_last_error());
}
echo "Listen socket....";
if(!socket_listen($socket_desc)){//Прослушиваем соединение на сокете
throw new Exception('Ошибка послушки сокета'.socket_last_error());
}
echo "Accept socket....";
do{
$accept_socket = socket_accept($socket_desc);//Принимаем соединение.
if(!$accept_socket){
throw new Exception('Невозможно принять соединение'.socket_last_error());
}
$id = uniqid('user_');
$msg = "Hello $id\n";
socket_write($accept_socket, $msg);
}
while(true);
socket_close($socket_desc);//Закрываем сокет
}
catch(Exception $e){
echo $e->getMessage();
}
$address = "127.0.0.1";
$port = 1000;
try{
$client_socket_desc = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);//Создаем сокет.Получаем дескриптор для соединения.
if (!$client_socket_desc) {
throw new Exception('Ошибка создания сокета'.socket_strerror(socket_last_error()));
}
echo 'Соединение с сервером ... ';
if (!socket_connect($client_socket_desc,$address,$port)) {
throw new Exception('Ошибка соединения с сервером'.socket_last_error());
}
$txt = socket_read($client_socket_desc,2096,PHP_NORMAL_READ);//Зачитываем буфер сокета (Привет user_*********)
echo $txt;
socket_close($client_socket_desc);
}
catch(Exception $e){
echo $e->getMessage();
}
Answer the question
In order to leave comments, you need to log in
Is it possible to do without Ajax, implement it through sockets?in order to send something to the socket you need to somehow get it from the browser.
What is the difference between TCPsockets (which I currently use) and WebSockets, which is better?which is better depends on the task.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question