簡體   English   中英

創建客戶端和服務器端套接字連接,並在php中保持連接

[英]Creating a client and server side socket connection and keeping it connected in php

如果我們在服務器端創建一個套接字,那么它會無限循環地運行,我們不能為客戶端做這樣的事情嗎? 我們可以無限循環地營造傾聽情緒嗎? 我是否每次都需要為此創建一個新的套接字?

這是我的代碼,只寫一次,當我嘗試在socket_read之后寫時,它不起作用。

服務器端代碼

<?php
$host = "192.168.56.1";
$port = 8080;
$message = "Hello Client";
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
$result = socket_listen($socket) or die("Could not set up socket listener\n");
echo 'listining ip '.$host." at port ".$port;
while(true){
$com = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($com, 1024) or die("Could not read input\n");
$input = trim($input);
echo '
Client says: '.$input;
socket_write($com, $message , strlen ($message)) or die("Could not write output\n");
}
echo '
server closed';
socket_close($com);
socket_close($socket);
?>

客戶端代碼

<?php
$host    = "192.168.56.1";
$port    = 8080;
$message = "Hello Server side";
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_connect($socket, $host, $port) or die ("Could not connect to server\n");

socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");
$result = socket_read($socket, 1024) or die("Could not read server response\n");
socket_write($socket,$message, strlen($message)) or die("Could not send data to server\n");

echo "Server  says :";//.$result;
socket_close($socket);
?>

如果我們在服務器端創建一個套接字,那么它會無限循環地運行,我們不能為客戶端做這樣的事情嗎? 我們可以無限循環地營造傾聽情緒嗎?

當然-如果您的服務器和客戶端嚴格按順序發送和接收,則只需將客戶端中socket_read行更改為

while ($result = socket_read($socket, 1024))

我是否每次都需要為此創建一個新的套接字?

不,您一定不能,因為它不會是同一連接。

但對於處理多個連接和斷開連接的更完整的服務器示例,請參見。 這個答案 如何使用套接字為php中的聊天程序編寫服務器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM