/* 监听sockfd描述符 */
if(listen(sockfd,5)==-1) /*5为请求队列的最大请求数*/
{
printf("Listen error:%s\n\a",strerror(errno));
exit(1);
}
while(1)
{
/* 服务器阻塞,直到客户程序建立连接 */
sin_size=sizeof(struct sockaddr_in);
if((new_fd=accept(sockfd,(struct sockaddr *)(&client_addr),&sin_size
))==-1)
{
printf("Accept error:%s\n\a",strerror(errno));
exit(1);
}
/*inet_ntoa的作用是将一个32位Ipv4地址转换为相应的点分十进制数串*/
printf("Server get connection from %s\n",inet_ntoa(client_addr.sin_addr));
/*向客户端发送hello字符数组的内容*/
myread(hello);
if(write(new_fd,hello,strlen(hello))==-1)
{
printf("Write Error:%s\n",strerror(errno));
exit(1);
}
/* 这个通讯已经结束 */
close(new_fd);
}/* while结尾处*/
close(sockfd);
exit(0);
}
client.c
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
int sockfd;
char buffer[1024];
struct sockaddr_in server_addr;
struct hostent *host;
int portnumber,nbytes;
/* 客户程序开始建立 sockfd描述符 */
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("Socket Error:%s\a\n",strerror(errno));
exit(1);
}
/* 客户程序填充服务端的资料 */
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(10240);/*主机字节序转换为网络字节序*/
server_addr.sin_addr.s_addr=inet_addr("server端IP");
/* 客户程序发起连接请求 */
if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
printf("Connect Error:%s\a\n",strerror(errno));
exit(1);
}
/* 连接成功了 */
if((nbytes=read(sockfd,buffer,1024))==-1)
{
printf("Read Error:%s\n",strerror(errno));
exit(1);
}
buffer[nbytes]=’\0’;
printf("%s\n",buffer);
/* 结束通讯 */
close(sockfd);
exit(0);
}
责任编辑:小草