C语言 socket编程 客户端只send一次 但是服务器会循环执行这条命令 在线等
代码如下:server端:intmain(intagrc,char*argv[]){//一些定义性的东西while(1)//waitingforclient{comm_s...
代码如下:
server端:
int main(int agrc, char *argv[])
{
//一些定义性的东西
while(1) //waiting for client
{
comm_socket= accept(ser_socket, (struct sockaddr *)&cliaddr, &addrlen); /*start accept mode, waiting until a specific socket to respone*/
recv(comm_socket, recv_buff,sizeof(recv_buff), 0); /*detectsomeone is comming*/
printf("%s\n",recv_buff); //recevingentering-command
strcpy(welcome_buff,"Welcometo my server!\n"); /*sendingwelcome message*/
send(comm_socket,welcome_buff, sizeof(welcome_buff)+1, 0); // sending welcome message
while(1)
{
recv(comm_socket,recv_buff, sizeof(recv_buff), 0); /*receiveclient's command*/
printf("%s\n",recv_buff); //receving client command
send(comm_socket,send_buff, strlen(send_buff)+1, 0);
……有省略(没什么重要的)
}
}
}
个人觉得问题还是出在server端吧,client就不放了,client就是中规中矩的那种。
想实现client端等待user输入一个东西,然后send给server端,然后server端send一个回复给client端,然后client端可以再次输入,再次执行send和recv。
可是现在的问题是如果我在client端输入一个1,server端识别了这个1之后执行相应的命令然后send 2给客户端,然后server端不会再次等待client端user的输入,而是不断将1作为recv,不断send 2给客户端,求大神解答! 展开
server端:
int main(int agrc, char *argv[])
{
//一些定义性的东西
while(1) //waiting for client
{
comm_socket= accept(ser_socket, (struct sockaddr *)&cliaddr, &addrlen); /*start accept mode, waiting until a specific socket to respone*/
recv(comm_socket, recv_buff,sizeof(recv_buff), 0); /*detectsomeone is comming*/
printf("%s\n",recv_buff); //recevingentering-command
strcpy(welcome_buff,"Welcometo my server!\n"); /*sendingwelcome message*/
send(comm_socket,welcome_buff, sizeof(welcome_buff)+1, 0); // sending welcome message
while(1)
{
recv(comm_socket,recv_buff, sizeof(recv_buff), 0); /*receiveclient's command*/
printf("%s\n",recv_buff); //receving client command
send(comm_socket,send_buff, strlen(send_buff)+1, 0);
……有省略(没什么重要的)
}
}
}
个人觉得问题还是出在server端吧,client就不放了,client就是中规中矩的那种。
想实现client端等待user输入一个东西,然后send给server端,然后server端send一个回复给client端,然后client端可以再次输入,再次执行send和recv。
可是现在的问题是如果我在client端输入一个1,server端识别了这个1之后执行相应的命令然后send 2给客户端,然后server端不会再次等待client端user的输入,而是不断将1作为recv,不断send 2给客户端,求大神解答! 展开
1个回答
展开全部
recv(comm_socket,recv_buff, sizeof(recv_buff), 0); /*receiveclient's command*/
改成
int ret = recv(comm_socket,recv_buff, sizeof(recv_buff), 0); /*receiveclient's command*/
if ret == -1 || ret == 0
break
== -1 表示出错, =0 表示 socket 已经关闭。
改成
int ret = recv(comm_socket,recv_buff, sizeof(recv_buff), 0); /*receiveclient's command*/
if ret == -1 || ret == 0
break
== -1 表示出错, =0 表示 socket 已经关闭。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询