/*************************************************************************************************
**File: client.c
**Author: FreeKing
**Created: Augist 11th 2009
**Description: TCP协议的服务器端的实现
**********************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
//服务器要监听的本地端口号
#define myport 5000
//能够同时接受多少没有 accept的连接
#define backlog 10
int main()
{
int sockfd;
int newfd;
//自己的地址信息
struct sockaddr_in myaddr;
//连接者的地址信息
struct sockaddr_in theiraddr;
int sin_size;
if( (sockfd = socket(AF_INET, SOCK_STREAM,0)) == -1)
{
perror("socket error !");
exit(1);
}
//主机字节顺序
myaddr.sin_family = AF_INET;
//网络字节顺序,ushort
myaddr.sin_port = htons( myport );
//将运行程序机器的IP填充入s_addr
myaddr.sin_addr.s_addr = INADDR_ANY;
//将次结构的其余空间清0
bzero( &( myaddr.sin_zero ), 8 );
if( bind( sockfd, (struct sockaddr *)&myaddr, sizeof( struct sockaddr) ) == -1 )
{
perror( "bind error !" );
}
if(listen(sockfd, backlog) == -1)
{
perror("listen error" );
exit(1);
}
char recvbuf[100];
char sendbuf[100];
char tempbuf[100];
while(1)
{
sin_size = sizeof(struct sockaddr_in );
if( ( newfd = accept( sockfd, (struct sockaddr *) &theiraddr, &sin_size) ) == -1 )
{
perror( "accept error!") ;
}
printf( "server: got connection from %s/n", inet_ntoa( theiraddr.sin_addr) );
if( !fork() )
{
// if( 'q' != sendbuf[0])
//服务器端通过标准IO读写数据
if( send( newfd, fgets(sendbuf,100,stdin ), 100,0 ) == -1)
{
perror( "send error!" );
close( sockfd );
exit( 0 );
}
}
//等待所有的子进程都退出
}
close( sockfd );
close( newfd );
while(waitpid( -1, NULL, WNOHANG) >0 );
}
/*************************************************************************************************
**File: client.c
**Author: FreeKing
**Created: Augist 11th 2009
**Description: TCP协议的客户端的实现
*************************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
//服务器要监听的本地端口号
#define myport 5000
//一次所能接收的最大字节数
#define max 100
int main( int argc , char* argv[] )
{
int sockfd, numbytes;
char buf[max] = {0};
struct hostent *he;
//连接者的主机信息
struct sockaddr_in theiraddr;
if( (sockfd = socket(AF_INET, SOCK_STREAM,0)) == -1)
{
perror("socket error !");
exit(1);
}
//主机字节顺序
theiraddr.sin_family = AF_INET;
//网络字节顺序,ushort
theiraddr.sin_port = htons( myport );
//将运行程序机器的IP填充入s_addr
theiraddr.sin_addr.s_addr = INADDR_ANY;
//将次结构的其余空间清0
bzero( &( theiraddr.sin_zero ), 8 );
if( (connect(sockfd, (struct sockaddr *) &theiraddr, sizeof(struct sockaddr)) ) == -1 )
{
perror( "connect error!") ;
exit(1);
}
if( (numbytes = recv( sockfd, buf, max, 0 )) == -1 )
{
perror( "recv error!" );
exit(0);
}
buf[numbytes] = '/n';
printf("receive: %s", buf);
close( sockfd );
return 0;
}