Linux简单Socket编程示例

Server端:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main()
{
	int sockSrv = socket(AF_INET,SOCK_STREAM,0);
	
	struct sockaddr_in addrSrv;
	bzero(&addrSrv,sizeof(addrSrv));
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
	addrSrv.sin_port = htons(6000);
	bind(sockSrv, (struct sockaddr*)&addrSrv, sizeof(addrSrv));
	
	listen(sockSrv,10);
	
	struct sockaddr_in addrConn;
	int len = sizeof(addrConn);
	
	while(1)
	{
		int sockConn = accept(sockSrv,(struct sockaddr*)&addrConn, &len);
		
		char buf[100] = {0};
		int n = read(sockConn, buf, 100);
		printf("server recv:%s\n",buf);
		
		write(sockConn, "server\n", strlen("server\n"));
		
		close(sockConn);
	}
	
	close(sockSrv);
	
	return -1;
}


Client端:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main()
{
	int sockSrv = socket(AF_INET, SOCK_STREAM, 0);
	
	struct sockaddr_in addrSrv;
	bzero(&addrSrv, sizeof(addrSrv));
	addrSrv.sin_family = AF_INET;
	addrSrv.sin_addr.s_addr = inet_addr("127.0.0.1");
	addrSrv.sin_port = htons(6000);
	connect(sockSrv, (struct sockaddr*)&addrSrv, sizeof(addrSrv));
	
	write(sockSrv, "client\n", strlen("client\n"));
	
	char buf[100] = {0};
	int n = read(sockSrv, buf, 100);
	
	printf("client recv:%s\n",buf);
	
	close(sockSrv);
	
	return -1;
}


你可能感兴趣的:(Linux简单Socket编程示例)