gpt4 book ai didi

c++ - 编写 tcp 服务器——缓冲流

转载 作者:行者123 更新时间:2023-11-30 17:54:57 26 4
gpt4 key购买 nike

#include <sys/socket.h> // for socket(), bind(), listen(), accept()
#include <netinet/in.h> // for PF_INET, SOCK_STREAM, IPPROTO_TCP
#include <stdio.h> // for printf(), perror()
#include <unistd.h> // for read(), write(), close()
#include <string.h> // for bzero()

#define DEMO_PORT 9723


int main( void )
{
//-----------------------------------------
// create an unnamed socket for the server
//-----------------------------------------
int sock = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( sock < 0 )
{
perror( "opening stream socket" );
return -1;
}
printf( "\nsock=%d \n", sock );

//----------------------------------------
// construct a name for the server socket
//----------------------------------------
struct sockaddr_in self;
socklen_t nlen = sizeof self;
bzero( &self, sizeof self );
self.sin_family = AF_INET;
self.sin_port = htons( DEMO_PORT );
self.sin_addr.s_addr = htonl( INADDR_ANY );
if ( bind( sock, (sockaddr *)&self, nlen ) < 0 )
{
perror( "bind failed" );
return -1;
}
printf( "bind succeeded port: %d\n",DEMO_PORT);

//---------------------------------------------------------
// now create a connection queue and wait for some clients
//---------------------------------------------------------
if ( listen( sock, 5 ) < 0 )
{
perror( "listen failed" );
return -1;
}
printf( "listen succeeded \n" );


//---------------------------------------------------
// main loop to process clients' connection-requests
//---------------------------------------------------
while ( 1 )
{
sockaddr_in peer;
socklen_t plen = sizeof peer;
bzero( &peer, plen );

printf( "server waiting \n" );

int client = accept( sock, (sockaddr *)&peer, &plen );
if ( client < 0 ) { perror( "accept" ); break; }

//---------------------------------------------
// we can now read from or write to the client
//---------------------------------------------
char ch;
int index = 0;
char get[1024];

if ( read( client, &ch, 1 ) < 0 )
{
perror( "read" );
}


bool go = true;


while(go){

if(ch != '/' && ch != '\r'){

printf("read: %hhd\n", ch);

get[index] = ch;
printf( "got stuff: %s\n", get );

index++;

read(index, &ch, 1);


} else {

go = false;
index = 0;
close( client );
printf( "server responded, connection closed" );


}
}


//if ( write( client, &ch, 1 ) < 0 ) { perror( "write" ); break; }



}

close( sock );
printf( "\n" );
}

while(go) 看起来永远不会起作用,并且它的缓冲不正确。我没有看到缓冲区内的模式或它是如何工作的。

正确的做法是什么?排除一定数量的字节,将它们存储在字符串中,然后在到达换行符时终止读取?

最佳答案

您正在将索引传递到第二个读取调用中,您应该在其中传递客户端。

这可能不是您唯一的问题,但我认为这是其中之一。

关于c++ - 编写 tcp 服务器——缓冲流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14657776/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com