TCP编程一对多实例

本文介绍了一个简单的TCP服务端与客户端的实现过程。服务端能够接收来自客户端的消息,并返回当前系统时间。客户端则可以向服务端发送消息并接收响应。文章通过具体的代码示例详细解释了如何创建socket、绑定地址、监听连接请求、接受连接、发送和接收数据等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
	Content	: This file is a service
	 Time	: 2017-06-21
*/

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

#include "Color.h"

#define PORT 	8888
#define SIZE 	512
#define BACKLOG 100	

int SockFd;
bool flag = false;
char SystemTime[1024];

//实现获取系统时间的接口
void GetSystemTime(){

	struct	timespec time;
	struct  tm nowTime;

	clock_gettime(CLOCK_REALTIME,&time);
	localtime_r(&time.tv_sec,&nowTime);

	sprintf(SystemTime,"%04d-%02d-%02d %02d:%02d:%02d",nowTime.tm_year+1900,nowTime.tm_mon+1,nowTime.tm_mday,nowTime.tm_hour,nowTime.tm_min,nowTime.tm_sec);
	//printf("Time Buffer content is:%s\n",SystemTime);
}

//实现信号自处理方法
void SigFunction(int signo){
	printf("Service Will Closed...\n");
	sleep(3);
	close(SockFd);
	printf("Close Service Suceess!\n");
	exit(0);
}

int main(int argc,char* argv[]){
	
	//Create Socket
	SockFd = socket(AF_INET,SOCK_STREAM,0);
	if (SockFd == -1){
		printf("Create socket Failed:%s(Error:%d)\n",strerror(errno),errno);
		exit(-1);
	}else{
		printf("Create socket suceess!\nSockFd:%d\n",SockFd);
	}

	//Init sockaddr struct
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	//use sersockopt function
	int reuseaddr = 1;
	setsockopt(SockFd,SOL_SOCKET,SO_REUSEADDR,&reuseaddr,sizeof(int));

	//bind socket  and ip adress
	int result = bind(SockFd,(struct sockaddr*)&addr,sizeof(addr));
	if(result == -1){
		printf("Bind SockFd Failed:%s(Error:%d)\n",strerror(errno),errno);
		exit(-1);
	}else{
		printf("Bind Scoket Fd suceess!\nBind result:%d\n",SockFd);
	}

	//on bind suceess,usr listen function
	result = listen(SockFd,BACKLOG);
	if (result == -1){
		printf("listen Socket Failed:%s(Error:%d)\n",strerror(errno),errno);
		exit(-1);
	}else{
		printf("Listen Sucess!\nListen result:%d\n",result);
	}

	//enter the while begin accept connect
	signal(SIGINT,SigFunction);
	printf("If you want quit,please input: Ctrl+C\n");


	char recvBuffer[SIZE] = {0};
	flag = true;
	while(flag){
		struct sockaddr_in recv_addr;
		socklen_t recv_len = sizeof(recv_addr);
		int fd = accept(SockFd,(struct sockaddr*)&recv_addr,&recv_len);
		if (fd == -1){
			printf("Accept Failed:%s(Error:%d)\n",strerror(errno),errno);
			exit(-1);
		}else{
			printf("Accept Suceess!\nAccept result:%d\n",result);
		}

		char* ip = inet_ntoa(recv_addr.sin_addr);
		printf("Clinet: "BROWN"%s connected!\n",ip);

		//Create pid
		pid_t Pid;
		Pid = fork();
		if (Pid == -1){
			printf("Create pid failed:%s(Error:%d)\n",strerror(errno),errno);
			exit(-1);
		}
		if (Pid == 0){
			if (signal(SIGINT,SIG_DFL) == SIG_ERR){
				perror("signal");
				exit(-1);
			}
			close(SockFd);
			while(flag){
				result = recv(fd,recvBuffer,sizeof(recvBuffer),0);
				if (result < 0){
					printf("Anything have not recved:%s(Error:%d)\n",strerror(errno),errno);
					exit(-1);
				}
				if(!strcmp(recvBuffer,"bye")){
					printf("Clinet :%s Will OffLine\n",ip);
					break;
				}
				printf("From Clinet: %s Msg is:%s\n",ip,recvBuffer);

				//result = send(fd,"Msg Recved",12,0);
				GetSystemTime();
				result = send(fd,SystemTime,sizeof(SystemTime),0);
				//if (result == -1){
				//	printf("Send Msg to Client Failed:%s(Error:%d)\n",strerror(errno),errno);
				//	exit(-1);
				//}
			}
			close(fd);
			exit(0);
		}
		close(fd);
		//flag = false;
	}
	return 0;
}

Clinet:此篇文章是为了回顾前几天看的TCP部分基础的点,临时敲的,如有错还请指出!

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

#define PORT 8888
#define BUFFERSIZE 1024

#define log printf

bool Flag = false;

int main(int argc, char* argv[]) {

	int SockFd;
	int Result;
	struct sockaddr_in ClinetAddr;

	SockFd = socket(AF_INET, SOCK_STREAM, 0);
	if (SockFd == -1) {
		log("Create SockFd Failed:%s(Error:%d)\n", strerror(errno), errno);
		exit(-1);
	}
	log("Create SockFd Successfull!\n");

	ClinetAddr.sin_family = AF_INET;
	ClinetAddr.sin_port = htons(PORT);
	ClinetAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	Result = connect(SockFd, (struct sockaddr*)&ClinetAddr, sizeof(sockaddr));
	if (Result == -1) {
		log("Connect to Service Failed:%s(Error:%d)\n", strerror(errno), errno);
		exit(-1);
	}

	char MsgBuffer[BUFFERSIZE] = { 0 };
	Flag = true;
	while (Flag) {
		log("Enter you want to send to Service:\n");
		fgets(MsgBuffer, sizeof(MsgBuffer), stdin);

		Result = send(SockFd, MsgBuffer, sizeof(BUFFERSIZE), 0);
		if (Result < 0) {
			log("Send Message to Service Failed:%s(Error:%d)\n", strerror(errno), errno);
			exit(-1);
		}

		if (!strcmp(MsgBuffer, "bye")) {
			log("Clinetg Will be quit...\n");
			Sleep(3);
			break;
		}

		char RecvBuffer[BUFFERSIZE] = { 0 };
		Result = recv(SockFd, RecvBuffer, sizeof(RecvBuffer), 0);
		if (Result < 0) {
			log("Recv Message Failed from Service:%s(Error:%d)\n", strerror(errno), errno);
			exit(-1);
		}
		log("From Service Message:%s\n", RecvBuffer);
	}
	close(SockFd);
	return 0;
}



Rebuild started: Project: Project *** Using Compiler &#39;V6.22&#39;, folder: &#39;E:\Keil_v5\ARM\ARMCLANG\Bin&#39; Rebuild target &#39;Target 1&#39; assembling startup_stm32f10x_md.s... Start/core_cm3.c(445): error: non-ASM statement in naked function is not supported 445 | uint32_t result=0; | ^ Start/core_cm3.c(442): note: attribute is here 442 | uint32_t __get_PSP(void) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(465): error: parameter references not allowed in naked functions 465 | "BX lr \n\t" : : "r" (topOfProcStack) ); | ^ Start/core_cm3.c(461): note: attribute is here 461 | void __set_PSP(uint32_t topOfProcStack) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(479): error: non-ASM statement in naked function is not supported 479 | uint32_t result=0; | ^ Start/core_cm3.c(476): note: attribute is here 476 | uint32_t __get_MSP(void) __attribute__( ( naked ) ); | ^ Start/core_cm3.c(499): error: parameter references not allowed in naked functions 499 | "BX lr \n\t" : : "r" (topOfMainStack) ); | ^ Start/core_cm3.c(495): note: attribute is here 495 | void __set_MSP(uint32_t topOfMainStack) __attribute__( ( naked ) ); | ^ 4 errors generated. compiling core_cm3.c... compiling misc.c... compiling system_stm32f10x.c... compiling stm32f10x_adc.c... compiling stm32f10x_dac.c... compiling stm32f10x_exti.c... compiling stm32f10x_dbgmcu.c... compiling stm32f10x_dma.c... compiling stm32f10x_crc.c... compiling stm32f10x_cec.c... compiling stm32f10x_bkp.c... compiling stm32f10x_can.c... compiling stm32f10x_flash.c... compiling stm32f10x_pwr.c... compiling stm32f10x_fsmc.c... compiling stm32f10x_
03-31
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值