本文介绍了使用tcp / ip进行双向客户端服务器通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我使用tcp / ip协议开发了服务器和客户端代码,使客户端能够将数据发送到服务器并收到相同的数据从服务器到客户端。



我想知道如何让客户端始终保持打开状态,就像服务器一样。我不应该每次都继续执行客户。



我提供的代码供进一步参考



服务器代码:

Hi,

I have developed a server and client code using tcp/ip protocol, which enables the client to send data to server and the same data is received from server to client.

I would like to know how to keep the client open all the time, same like as server. I should not keep executing the client every time.

I am giving the code for further reference

Server code:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
void str_echo(int s)
{
	FILE *fp,*fp1;
	char buf[2000];
	//receiving data from client
	recv(s,buf,2000,0);
	puts("Message from Client...");
	fputs(buf,stdout);
	send(s,buf,2000,0);
	}
int main()
{
 	int ls,cs,len;
 	struct sockaddr_in serv,cli;
 	pid_t pid;
 	puts("I am Server...");
	//creating socket
	ls=socket(AF_INET,SOCK_STREAM,0);
 	puts("Socket Created Successfully...");
	//socket address structure
 	serv.sin_family=AF_INET;
 	serv.sin_addr.s_addr=INADDR_ANY;
 	serv.sin_port=htons(6777);
 	bind(ls,(struct sockaddr*)&serv,sizeof(serv));
 	puts("Binding Done...");
 	listen(ls,3);
 	puts("Listening for Client...");
 	for(; ;)
 	{
		len=sizeof(cli);
		//accepting client connection
		cs=accept(ls,(struct sockaddr*)&cli,&len);
		puts("\nConnected to Client...");
		//creating child process
		if((pid=vfork()) == 0)
		{
			puts("Child process created...");
			close(ls);
			str_echo(cs);
			close(cs);
			exit(0);
		}
	close(cs);
 	}
 	return 0;
}







客户代码:






Client Code:

#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
void str_echo(int s)
{
	char buf[2000],buf1[2000];
	puts("Enter the Message...");
	fgets(buf,2000,stdin);
	send(s,buf,2000,0); //sending data to server
	//receiving data from server
	recv(s,buf1,2000,0);
	puts("Message from Server...");
	//fputs(buf1,stdout);
	puts(buf1);
}
int main()
{
	int ls;
 	struct sockaddr_in cli;
 	puts("I am Client...");
	/*creating socket*/
 	ls=socket(AF_INET,SOCK_STREAM,0);
 	puts("Socket Created Successfully...");
	/*socket address structure*/
 	cli.sin_family=AF_INET;
 	cli.sin_addr.s_addr=inet_addr("127.0.0.1");
 	cli.sin_port=htons(6777);
	/*connecting to server*/
 	connect(ls,(struct sockaddr*)&cli,sizeof(cli));
 	puts("Connected with Server...");
	str_echo(ls);
 	close(ls);
 	return 0;
}

推荐答案

str_echo(ls);

你可以对于(;;)
{
str_echo(ls);


you could do

for (; ; )
{
    str_echo(ls);
    sleep(60 * 1000);   // for example to sleep 1 minute between loops
}





我不是说它是一个好主意,只是一个可能的(我建议不要以此为例,如果你这样做,你必须通过它的PID来终止进程)



Im not saying its a good idea, just a possible one (I recommend NOT running this as an example, you'll have to kill the process by its PID if you do)


这篇关于使用tcp / ip进行双向客户端服务器通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 09:59