client 和 server 通讯实例(TCP协议使用 select 函数)

本文提供了一个使用TCP协议并通过select函数实现的client-server通信示例。在Linux环境下,展示了服务器端和客户端的代码实现,以及双方交互的执行结果。客户端通过键盘输入数据,输入'eXit'退出。服务器端接收到数据并响应,当接收到'eXit'时关闭连接。
摘要由CSDN通过智能技术生成

client 和 server 通讯实例(TCP协议使用 select 函数)

先用标准输入(键盘输入)演示 select 函数的使用:

/****** sample.c for Linux ******/ 

#include <stdio.h>
#include <string.h>
#include <sys/select.h>

#define STDIN 0

int main()
{
	int  n, flag;
	char buf[80];
	fd_set fds;
	struct timeval tv;
	int fd = STDIN;

	printf("type \"eXit\" to exit.\n");

	flag = 1;
	while(1 == flag)
	{
		tv.tv_sec=10;
		tv.tv_usec=0;
		FD_ZERO(&fds);
		FD_SET(fd,&fds);

		//[] switch(select(fd+1, &fds, NULL, NULL, &tv))
		switch(select(FD_SETSIZE, &fds, NULL, NULL, &tv))
		{
		case -1:  // select错误
			printf("返回错误。\n");
			flag = -1;
			break;
		case 0: //再次轮询
			printf("超时。\n");
			break;
		default:
			if(FD_ISSET(fd, &fds)) 
			{
				fgets(buf, 20, stdin);

				n = strlen(buf);
				if('\n' == buf[n-1])
					buf[n-1] = '\0';
				printf("数据:%s\n", buf);

				if(0 == strcmp(buf, "eXit")) //退出程序?
				{
					flag = 0;
					break;
				}
				
			}
			break;
		}
	}

	return flag;
}

执行结果示例:

[root@localhost ~]# ./sample
type "eXit" to exit.
asdf
数据:asdf
asdfg
数据:asdfg
sdf
数据:sdf
超时。
超时。
eXit
数据:eXit
[root@localhost ~]#


服务器端代码(Linux系统,TCP协议):

/****** server.c for Linux ******/ 

#include <stdio.h> 
#include <errno.h> 
#include <string.h> 
#include <sys/socket.h> 
#include <arpa/inet.h>

#define STDIN 0

int main(int argc, char *argv[]) 
{ 
	int    n, flag;
	char   buf[1024];
	fd_set fds;
	struct timeval tv;
	struct sockaddr_in   client_addr; 
	int    sockfd, fd, sin_size;
	int                  port; 
	struct sockaddr_in   addr; 
	int    fdstd = STDIN;


	if(argc
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值