1.服务器端:
/*
* server.c
*
* Created on: Nov 20, 2012
* Author: gentoo
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#define SERVER_PORT 8999
#define BUFFER 1024
int main(int argc, char * argv[]) {
int listenfd; //用于监听
int connfd; //用于连接
struct sockaddr_in seraddr; //socket的地址信息结构体
char buff[BUFFER]; //字符串缓冲区
time_t ticks; //时间
//创建一个监听的socket
if ( (listenfd=socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("create sock error!\n");
exit(1);
}
//清空地址结构体并设置相应的信息
bzero(&seraddr, sizeof(seraddr));
seraddr.sin_family = AF_INET; //使用的协议:TCP/IP
seraddr.sin_port = htons(SERVER_PORT); //用于监听的端口
seraddr.sin_addr.s_addr = htonl(INADDR_ANY); //服务器端的IP地址,INADDR_ANY表示由系统自动获取
//进行绑定
if ( bind(listenfd, (struct sockaddr *)&seraddr, sizeof(seraddr))< 0 )
{
perror("bind sock error!\n");
exit(1);
}
//进行监听
if ( (listen(listenfd, 4)) < 0 )
{
perror("listen error!\n");
exit(1);
}
//等待客户端的请求
for( ; ; )
{
//进行阻塞,直到有一个客户端发起请求
connfd = accept(listenfd, NULL, NULL);
ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));
//向连接中的socket通道写一些字符串
write(connfd, buff, strlen(buff));
//关闭该次的连接
close(connfd);
}
return EXIT_SUCCESS;
}
/*
* Client.c
*
* Created on: Nov 20, 2012
* Author: gentoo
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFER 1024
#define SERVER_PORT 8999
int main(int argc, char * argv[]) {
//用于连接的socket
int sockfd;
//读取了多少个字节
int readBytes;
//信息的接收
char recieve[BUFFER+1];
//服务器端的地址结构体信息
struct sockaddr_in servaddr;
if ( argc != 2 )
{
perror("IP is required!\n");
exit(1);
}
//创建一个socket
if ( (sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("crate socket error!\n");
}
//清空地址信息结构体并设置相应的信息
bzero(&servaddr, sizeof(servaddr));;
servaddr.sin_family = AF_INET; //所用的协议
servaddr.sin_port = htons(SERVER_PORT); //所要连接到服务器的端口号
//将参数argv[1]的字符串转化为IP地址
if ( (inet_pton(AF_INET, argv[1], &servaddr.sin_addr)) <= 0 )
{
perror("IP transform error!\n");
exit(1);
}
//进行连接
if ( (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0 )
{
perror("connected error!\n");
exit(1);
}
//读取服务器端发送的信息并将其输出到stdout中
while ( (readBytes=read(sockfd, recieve, BUFFER)) > 0 )
{
recieve[readBytes] = 0;
if ( fputs(recieve, stdout) == EOF )
{
fprintf(stdout, "fputs error!\n");
}
}
if ( readBytes < 0 )
{
perror("read error!\n");
}
return EXIT_SUCCESS;
}