欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单的stream socket例子

程序员文章站 2022-04-09 13:10:51
...

服务器端:

#include<stdio.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<stdlib.h>
int main(){
	int sock_server, sock_client;
	struct sockaddr_in server_addr, client_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(6666);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);  //inet_addr("127.0.0.1")
	sock_server = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_server < 0){
		printf("server socket create error!\n");
		exit(1);		
	}
	int server_len = sizeof(server_addr);
	if(bind(sock_server, (struct sockaddr*)&server_addr, server_len) < 0){
		printf("bind server socket error\n");
		exit(0);
	}
	if(listen(sock_server, 5) < 0){
		printf("serever socket listen error\n");
		exit(1);
	}
	while(1){
//		printf("wait\n");
		int client_len = sizeof(client_addr);
		sock_client = accept(sock_server, (struct sockaddr*)&client_addr, (socklen_t*)&client_len);
		if(sock_client < 0){
			printf("Accept error\n");
			exit(1);
		}
//		printf("Accepted\n");
		int pid = fork();
		if(pid == 0){
			char buf[100];
			recv(sock_client, buf, 100, 0);
			printf("Message from client: %s\n", buf);
			send(sock_client, "Hello client", 100, 0);
			struct sockaddr_in server;
			server_len = sizeof(server);
			getsockname(sock_client, (struct sockaddr*)&server, (socklen_t*)&server_len);
			char local_addr[20];
			if(inet_ntop(AF_INET, (void*)&server.sin_addr, local_addr, sizeof(local_addr))){
//				printf("转换成功\n");
				printf("information: %s %d\n", local_addr, ntohs(server.sin_port));
			}
			else
				printf("地址转换失败\n");
//			printf("AAA\n");
			while(1)  //不调用close(),导致tcp状态一直处于close_wait状态
				;
			close(sock_client);
		}
	}
	close(sock_server);
	return 0;
}



客户端:

#include<stdio.h>
#include<netinet/in.h>
#include<unistd.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<string.h>
int main(){
	int sock_server, sock_client;
	struct sockaddr_in server_addr, client_addr;
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(6666);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	sock_client = socket(AF_INET, SOCK_STREAM, 0);
	if(sock_client < 0){
		printf("client socket create error!\n");
		exit(1);		
	}
	if(connect(sock_client, (struct sockaddr*)&server_addr, sizeof(server_addr)) != -1){
			printf("client success");
			char buf[100] = "Hello server";
			send(sock_client, buf, 100, 0);
			recv(sock_client, buf, 100, 0);
			printf("Message from server: %s\n", buf);
			int client_len = sizeof(client_addr);
			while(1)
				;
			close(sock_client);
	}else{
		printf("Connect error\n");
		exit(1);
	}
	return 0;
}