UDP传输原理
UDP传输不需要连接, 发送端只需要把自己的消息打包好(UDP报文), 然后从电脑上发到因特网即可, 不会有任何的确认帧来反馈给你.
PHP-Server
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <?php include_once "actionLoad.php";
define("SERVER","udp://127.0.0.1:9998");
$socket = stream_socket_server(SERVER, $errno, $errstr, STREAM_SERVER_BIND);
!$socket ? die("$errstr ($errno)") : null; echo "udp server had started...\nthe port is 9998...\n"; do { $request_msg = stream_socket_recvfrom($socket, 1024 * 2, 0, $client); echo $request_msg."\n"; coreHandler($socket, $request_msg, $client); } while ($request_msg !== false);
|
Run Server
1 2 3
| ➜ php server.php udp server had started... the port is 9998...
|
PHP-Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
function udpRequest($sendMsg = '', $ip = '127.0.0.1', $port = '9998') { $handle = stream_socket_client("udp://{$ip}:{$port}", $errno, $errstr); !$handle ? die("ERROR: {$errno} - {$errstr}\n") : null; fwrite($handle, $sendMsg . "\n"); $result = fread($handle, 1024); fclose($handle); return $result; }
$result = udpRequest(json_encode(array("code" => 4, "name" => "alicfeng"))); echo $result;
|
Run Client
C-Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <arpa/inet.h> #include <unistd.h>
#define LOG_SERV_ADDR "127.0.0.1"
#define LOG_SERV_PORT 9998
#define LOG_ENV_DEV 1
void send_msg_udp(char *message) { if(LOG_ENV_DEV!=1){ return; } int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_DGRAM, 0);
bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(LOG_SERV_PORT); if (inet_pton(AF_INET, LOG_SERV_ADDR, &servaddr.sin_addr) <= 0) { return; } if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) { perror("connect udp error"); return; } write(sockfd, message, strlen(message)); }
int main(int argc, char **argv) { send_msg_udp("alicFeng在扔数据..."); return 0; }
|
Run Client
1
| gcc -o client client.c && ./client
|
文章来源:
价值源于技术,贡献源于分享