您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

linux下c语言实现TCP网络编程对话模拟socket

文章目录

    • 程序基本功能:
    • 服务器端:
    • 客户端:

程序基本功能:

编写使用TCP协议的服务器程序和客户端程序;两者建立连接实现模拟对话的功能,即:客户端向服务器发送字符串,服务器打印收到的字符串,并向客户端发送应答。

服务器端:

//server
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFSIZE 1024
#define PORT 8000
void main(void){
	int client_sockfd, my_sockfd;
	struct sockaddr_in my_addr;
	struct sockaddr_in client_addr;
	int len;
	int sin_size;
	char buf[BUFSIZE];
	memset(&my_addr, 0, sizeof(my_addr));//清空
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(PORT);
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	//设置协议
	if((my_sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){
		printf("socket error\n");
		exit(1);
	} 
	//绑定地址
	if(bind(my_sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr))==-1){
		printf("bind error\n");
		exit(1);
	}
	//设定最大连接数
	if(listen(my_sockfd, 5)==-1){
		printf("listen error\n");
		exit(1);
	}
	sin_size = sizeof(struct sockaddr_in);
	//等待客户端连接,从listen队列中取出连接
	if((client_sockfd = accept(my_sockfd, (struct sockaddr*)&my_addr, &sin_size))==-1){
		printf("accept error\n");
		exit(1);
	}
	printf("client connected\n");
	len = send(client_sockfd,"welcome!\n", 9, 0);
	while((len = recv(client_sockfd, buf, BUFSIZE, 0))>0){
		buf[len] = '\0';
		printf("message from client:\n%s\nEnter your anwser:\n", buf);
		scanf("%s", buf);
		if(send(client_sockfd, buf, strlen(buf), 0) < 0){
	printf("send error\n");
	exit(1);
	}
	}
	close(my_sockfd);
	close(client_sockfd);
}

客户端:

//client
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#define BUFSIZE 1024
#define PORT 8000
void main(void){
	int len;
	char buf[BUFSIZE];
	struct sockaddr_in clientaddr;
	int sockfd;
	memset(&clientaddr, 0, sizeof(clientaddr));
	clientaddr.sin_family = AF_INET;
	clientaddr.sin_port = htons(PORT);
	clientaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
	if((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){
		printf("socket error\n");
		exit(1);
	}
	if((connect(sockfd, (struct sockaddr*)&clientaddr, sizeof(struct sockaddr))) == -1){
		printf("connect error\n");
		exit(1);
	}
	printf("connected\n");
	len = recv(sockfd, buf, BUFSIZE, 0);
	buf[len] = '\0';
	printf("Message from server:\n%s\nEnter your anwser here:\n", buf);
	scanf("%s", buf);
	while(1){
		if(strcmp(buf, "quit")== 0)
	break;
		if(send(sockfd, buf, strlen(buf), 0) < 0){
			printf("send error\n");
			exit(1);
		}
		len = recv(sockfd, buf, BUFSIZE, 0);
		buf[len] = '\0';
		printf("Message from server:\n%s\nEnter your anwser here:\n", buf);
		scanf("%s", buf);
	}
	close(sockfd);
}

参考博客


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进