TCP网络编程基本模型:
UNIX环境高级编程435页。
程序例程:
服务器:
#include
#include
#include
#include
#include
#include
#define portnumber 3333
int main( int argc, char **argv )
{
int
sockfd;
int
new_fd;
int
sin_size;
int
nbytes;
char
buffer[1024];
struct sockaddr_in
server_addr;
struct sockaddr_in
client_addr;
if( (sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1 )
{
perror( "socket error\n" );
exit( 1 );
}
bzero( &server_addr, sizeof(struct sockaddr_in) );
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl( INADDR_ANY );
server_addr.sin_port = htons( portnumber );
if( bind(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1 )
{
perror( "bind error\n" );
exit( 1 );
}
if( listen(sockfd, 5) == -1 )
{
perror( "listen error\n" );
exit( 1 );
}
sin_size = sizeof( struct sockaddr_in );
while( 1 )
{
if( (new_fd=accept(sockfd, (struct sockaddr *)(&client_addr), &sin_size)) == -1 )
{
perror( "accept error\n" );
exit( 1 );
}
fprintf( stdout," server get %s ", inet_ntoa(client_addr.sin_addr) );
if( (nbytes=read(new_fd, buffer, 1024)) == -1 )
{
perror( "read error\n" );
exit( 1 );
}
buffer[nbytes] = '\0';
printf( "received %s\n", buffer );
close( new_fd );
}
exit( 0 );
}
客户端:
#include
#include
#include
#include
#include
#define portnumber 3333
int main( int argc, char **argv )
{
int sockfd;
char buffer[1024];
struct sockaddr_in server_addr;
sockfd = socket( AF_INET, SOCK_STREAM, 0 );
bzero( &server_addr, sizeof(server_addr) );
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( portnumber );
server_addr.sin_addr.s_addr = inet_addr( "127.0.1.1" );
if( connect(sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr)) == -1 )
{
perror( "connet error\n" );
exit( 1 );
}
printf( "please input char: \n");
fgets( buffer, 1024, stdin );
write( sockfd, buffer, strlen(buffer) );
close( sockfd );
exit( 0 );
}
遇到的问题:
刚开始由于在客户端中没有建立套接字,即
sockfd = socket( AF_INET, SOCK_STREAM, 0 );这一句,导致connect文件总是返回pemission denied。
多线程TCP编程:
while( 1 )
{
if( (new_fd=accept(sockfd, (struct sockaddr *)(&client_addr), &sin_size)) == -1 )
{
perror( "accept error\n" );
exit( 1 );
}
fprintf( stdout," server get %s\n ", inet_ntoa(client_addr.sin_addr) );
if( fork() == 0 )
{
if( (nbytes=read(new_fd, buffer, 1024)) == -1 )
{
perror( "read error\n" );
exit( 1 );
}
buffer[nbytes] = '\0';
printf( "received %s\n", buffer );
close( new_fd );
}
}
主要思想是一个线程处理连接任务,连接后的事务用创建的子进程处理
UNIX环境高级编程435页。
程序例程:
服务器:
#include
#include
#include
#include
#include
#include
#define portnumber 3333
int main( int argc, char **argv )
{
}
客户端:
#include
#include
#include
#include
#include
#define portnumber 3333
int main( int argc, char **argv )
{
}
遇到的问题:
刚开始由于在客户端中没有建立套接字,即
sockfd = socket( AF_INET, SOCK_STREAM, 0 );这一句,导致connect文件总是返回pemission denied。
多线程TCP编程:
while( 1 )
主要思想是一个线程处理连接任务,连接后的事务用创建的子进程处理