在进行编程之前,我们需要打开socket,打开方法见下:
>gedit .bashrc
add things as follow
exportPATH=/usr/local/php5/bin:$PATH //我的php安装在/usr/local/php5路径下
>source .bashrc
然后:
1. >cd/root/php-5.2.13/ext/sockets //我的php安装包放在/root下
2. >phpize
3. >./configure
4. >make
5. >make install
6. >cp /usr/local/lib/php.ini/usr/local/php5/lib/php.ini
7. >vi /usr/local/php5/lib/php.ini
add things as follow:
extension_dir ="/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/"
extension = "sockets.so"
8.>apachectl restart
好了,在重启apache后,我们就可以进行程序的编写了,这两个程序也是网上非常常见的程序,在次借用,也非常感谢程序的原创者。
1. 服务器端程序:server.c
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
main(){
int sock;
struct sockaddr_in server,client;
int recvd,snd;
int structlength;
char * server_ip = "128.168.10.1";
int port = 8888;
charrecvbuf[2000],sendbuf[2000];
char str1[]="I have received:\n";
memset((char *)&server,0,sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(server_ip);
server.sin_port = htons(port);
memset((char *)&client,0,sizeof(client));
client.sin_family = AF_INET;
client.sin_addr.s_addr = htonl(INADDR_ANY);
client.sin_port = htons(port);
if((sock = socket (AF_INET,SOCK_DGRAM,0)) < 0){
printf("socket create error!\n");
exit(1);
}
structlength = sizeof(server);
if( bind(sock,(struct sockaddr *)&server,structlength) < 0){
printf("socket bind error!\n");
perror("bind");
exit(1);
}
while(1){
structlength =sizeof(client);
printf("waiting.......\n");
recvd = recvfrom(sock,recvbuf,sizeof(recvbuf),0,
(struct sockaddr *) &client,&structlength);
if(recvd < 0){
perror("recvfrom");
exit(EXIT_FAILURE);
}
else{