今天开始 学下Linux网络编程,主要是想学C,菜鸟也来玩玩哈,写了个简单的聊天室。。
首先用C建个socket服务,开始接收请求,并写入文件(其他代码省略)
while(1) {
len = sizeof(struct sockaddr);
if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &len)) == -1) {
perror("accept");
exit(errno);
}
else printf("server: got connection from %s, port %d, socket %d/n",inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
bzero(buf, MAXBUF + 1);
strcpy(buf, "send msg");
bzero(buf, MAXBUF + 1);
len = recv(new_fd, buf, MAXBUF, 0);
if(len > 0){
printf("receive:'%s',%d/n", buf, len);
//写入本地
if ((stream = fopen("/tmp/leaveword.txt", "a")) == NULL)
{
fprintf(stderr, "Cannot open output file./n");
return 1;
}
strcat(buf,"/n");
printf("%d",len);
flock(stream,LOCK_EX);
fwrite(buf, strlen(buf), 1, stream);
flock(stream,LOCK_UN);
fclose(stream);
}
else printf("error '%s'/n", errno, strerror(errno));
close(new_fd);
}
之后编译下
gcc -o s s.c
./s 88
php前端:
$host = "127.0.0.1";
$port = 88;
set_time_limit(0);
$commonProtocol = getprotobyname("tcp");
$socket = socket_create(AF_INET, SOCK_STREAM, $commonProtocol) or die("Could not create
socket/n");
$connection=socket_connect($socket,$host,$port);
$Socket_logintext=$_POST['username']."(".GTNGetIP()."):".$_POST['contents'];
socket_send($socket,$Socket_logintext,strlen($Socket_logintext),0x4);
之后怎么取数据,怎么定时刷新就看自己的了,怎么玩都行,就到这里吧,下次在写,然后做下性能测试,看能同时支持多少人