spacer.gif//服务器程序:

#include  <stdio.h>

#include  <stdlib.h>

#include  <string.h>

#include  <arpa/inet.h>

#include  <sys/types.h>

#include  <sys/socket.h>

#include  <unistd.h>

#define PORT  82

#define BUFSIZE  512

char buf[BUFSIZE+1];

int main()

{

//1  创建套接字

int sockfd=socket(AF_INET,SOCK_STREAM,0);

//2  设置地址结构体

struct sockaddr_in  svraddr;

svraddr.sin_family=AF_INET;//使用internet  协议

svraddr.sin_port=htons(PORT);

inet_aton("0.0.0.0",&svraddr.sin_addr);

//3  绑定

bind(sockfd,(struct  sockaddr*)&svraddr,sizeof(svraddr));

//4  监听

listen(sockfd,128);

while(1)

{

int new_fd=accept(sockfd,NULL,NULL); //5  接收

while(1)

{

int z=read(new_fd,buf,BUFSIZE);//6  读取套接字

if(z==0){printf("client  close !");break;};

buf[z]='\0';

printf("%s\r\n",buf);//打印

}

}

}


spacer.gif//客户端程序cli.c

#include  <stdio.h>

#include  <stdlib.h>

#include  <string.h>

#include  <arpa/inet.h>

#include  <sys/types.h>

#include  <sys/socket.h>

#include  <unistd.h>

#define PORT  82

#define BUFSIZE  512

char buf[BUFSIZE+1];

int main()

{

//1  创建一个体套接字

int sockfd=socket(AF_INET,SOCK_STREAM,0);

//2  设置addr 结构体

struct sockaddr_in  svraddr;

svraddr.sin_family=AF_INET;//使用internet  协议

svraddr.sin_port=htons(PORT);

inet_aton("127.0.0.1",&svraddr.sin_addr);

//3  连接服务器

connect(sockfd,(struct  sockaddr*)&svraddr,sizeof(svraddr));

while(1)

{

scanf("%s",buf);

write(sockfd,buf,strlen(buf)); //4  向套接字中写入字符串

}

}