C语言两个进程相互通信—socket

直接贴代码吧

client.c

 

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
	int sockfd;
	int len;
	struct sockaddr_in address;
	int result;
	int i,byte;
	char char_recv,char_send;
	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
	{
		perror("socket");
		exit(EXIT_FAILURE);
	}
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr("127.0.0.1");
	address.sin_port = 8080;
	len = sizeof(address);
	if((result = connect(sockfd,(struct sockaddr *)&address,len)) == -1)
	{
		perror("connect");
		exit(EXIT_FAILURE);
	}

	printf("please enter the context you want to send to server :");
	scanf("%c",&char_send);

	if(byte = send(sockfd,&char_send,1,0) == -1)
	{
		perror("send");
		exit(EXIT_FAILURE);
	}
	if(byte = recv(sockfd,&char_recv,1,0) == -1)
	{
		perror("recv");
		exit(EXIT_FAILURE);
	}
	printf("receive from server %c\n",char_recv);
	
	close(sockfd);
	exit(0);
}

 server.c

 

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
char dict(char temp)
{
	if(temp == 'Z')
	{
		return 'A';
	}
	return temp+1;
}
int main()
{
	int server_sockfd,client_sockfd;
	int server_len,client_len;
	struct sockaddr_in server_address;
	struct sockaddr_in client_address;
	int i,btye;
	char char_recv,char_send;
	
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
	server_address.sin_port = 8080;
	server_len = sizeof(server_address);
	
	server_sockfd = socket(AF_INET,SOCK_STREAM,0);
	
	bind(server_sockfd,(struct sockaddr *)&server_address,server_len);
	
	listen(server_sockfd,5);
	printf("server waiting for connect\n");
	
	client_len = sizeof(client_address);
	client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address,(socklen_t *)&client_len);
	
	if(btye = recv(client_sockfd,&char_recv,1,0) == -1)
	{
		perror("recv");
		exit(EXIT_FAILURE);
	}
	printf("receive from client is %c\n",char_recv);
	char_send = dict(char_recv);
	if(btye = send(client_sockfd,&char_send,1,0) == -1)
	{
		perror("send");
		exit(EXIT_FAILURE);
	}

	shutdown(client_sockfd,2);
	shutdown(server_sockfd,2); 
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值