UDP方式通信
服务器端server.c
/*server.c*/
#include
#include
#include
#include
#define SERV_PORT 8000
int main()
{
int sockfd,n,servaddr_len;
char * server_ip = "127.0.0.1";
char buf[80];
struct sockaddr_in server,client;
sockfd = socket (AF_INET,SOCK_DGRAM,0);
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(server_ip);
server.sin_port = htons(SERV_PORT);
servaddr_len = sizeof(server);
bind(sockfd,(struct sockaddr *) &server,servaddr_len);
listen(sockfd,6);
while(1)
{
printf("等待读取数据.......\n");
servaddr_len = sizeof(client);
n = read(sockfd,buf,sizeof(buf));
write(sockfd,buf,n);
printf("读取的数据为:%s\n",buf);
bzero(buf,sizeof(buf));
}
close(sockfd);
return 0;
}
客户端client.php
$server_ip="127.0.0.1";
$port = 8000;
if($_POST['submit'])
{
$buf=trim($_POST['buf']);
$sockfd=socket_create(AF_INET,SOCK_DGRAM,SOL_UDP)or die("创建失败");
socket_connect($sockfd,$server_ip,$port)or die("连接错误");
socket_write($sockfd,$buf,strlen($buf))or die("写入错误");
socket_read($sockfd,$buf,80);
echo $buf;
$buf="";
socket_close($sockfd);
}
?>
server.c文件通过gcc编译器编译
client.php通过浏览器运行
TCP方式
服务器端
/*server.c*/
#include
#include
#include
#include
#define SERV_PORT 8000
int main()
{
int sockfd,n,servaddr_len,client_len,connfd;
char * server_ip = "127.0.0.1";
char buf[80];
struct sockaddr_in server,client;
sockfd = socket (AF_INET,SOCK_STREAM,0);
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(server_ip);
server.sin_port = htons(SERV_PORT);
servaddr_len = sizeof(server);
client_len=sizeof(client);
bind(sockfd,(struct sockaddr *) &server,servaddr_len);
listen(sockfd,6);
while(1)
{
bzero(buf,sizeof(buf));
printf("等待读取数据.......\n");
connfd=accept(sockfd,(struct sockaddr *)&client,&client_len);
n = read(connfd,buf,sizeof(buf));
// write(connfd,buf,n);
printf("读取的数据为:%s\n",buf);
}
close(sockfd);
return 0;
}
客户端
$server_ip="127.0.0.1";
$port = 8000;
if($_POST['submit'])
{
$buf=trim($_POST['buf']);
$sockfd=socket_create(AF_INET,SOCK_STREAM,SOL_TCP)or die("创建失败");
socket_connect($sockfd,$server_ip,$port)or die("连接错误");
socket_write($sockfd,$buf,strlen($buf))or die("写入错误");
$a=socket_read($sockfd,80);
echo $a;
$buf="";
socket_close($sockfd);
}
?>
注意:1、tcp方式要设置安全级别及防火墙
centOS5.4设置方法为:系统->管理->安全级别及防火墙->SElinux选项卡
设置为允许即可
2、查看httpd_can_network_connect选项设置为on
centOS5.4设置方法为:在终端执行setsebool httpd_can_network_connect on 即可
本人推荐使用第二种方法
阅读(2332) | 评论(0) | 转发(0) |