【Linux网络编程】基于TCP单进程版本阻塞式客户端/服务器


实现基于TCP的C/S服务模型,服务器将客户端的输入回显给客户端。


服务器代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

int startup(const char* _ip, int port)
{
	int sock = socket(AF_INET,SOCK_STREAM, 0);
	if(sock<0)
	{
		perror("sock");
		exit(4);
	}
	int opt = 1;
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
	struct sockaddr_in local;
	local.sin_family = AF_INET;
	local.sin_addr.s_addr  = inet_addr(_ip);
	local.sin_port = htons(port);
	if(bind(sock, (struct sockaddr*)&local, sizeof(local)) != 0)
	{
		perror("bind");
		exit(5);
	}
	if(listen(sock, 5))
	{
		perror("listen");
		exit(6);
	}
	return sock;
}


static usage(const char* proc)
{
	printf("%s [ip] [port\n]", proc);
}

int main(int argc, char** argv)
{
	int listen_sock;
	if(argc != 3)
	{
		usage(argv[0]);
		exit(1);
	}

	listen_sock = startup(argv[1], atoi(argv[2]));
	struct sockaddr_in remote;
	socklen_t len = sizeof(remote);
	char buf[1024];
	while(1)
	{
		int sock = accept(listen_sock, (struct sockaddr*)&remote, &len);
		if(sock < 0)
		{
			perror("accept");continue;
		}
		printf("client ip : %s, prot : %d \n", inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
		while(1)
		{
			ssize_t s  = read(sock, buf, sizeof(buf) - 1);
			if(s > 0)
			{
				buf[s] = 0;
				printf("client say # %s\n", buf);
				write(sock , buf, strlen(buf));
			}
			else if(s == 0)
			{
				printf("client quit\n");
				break;
			}
		}
	}

	return 0;
}



客户端代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

static usage(const char* proc)
{
	printf("%s [ip] [port\n]", proc);
}

int main(int argc, char** argv)
{
	if(argc != 3)
	{
		usage(argv[0]);
		exit(1);
	}

	int sock = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in server;
	if(sock < 0)
	{
		perror("socket");
		return 1;
	}
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr(argv[1]);
	server.sin_port = htons(atoi(argv[2]));

	if(connect(sock ,(struct sockaddr*)&server, sizeof(server) ) < 0)
	{
		perror("connect");
		exit(4);
	}

	char buf[1024];

	while(1)
	{
		printf("please input #: ");
		fflush(stdout);
		ssize_t sread = read(0, buf, sizeof(buf)-1);
		if(sread > 0)
		{
			buf[sread-1] = 0;
			write(sock, buf, strlen(buf));
			printf("server $ %s\n", buf);
			read(sock, buf, sizeof(buf) - 1);
		}
	
	}



	close(sock);
}

截图:

服务端


客户端



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值