linux下面的tcp编程

首先要建立服务器建立起socket,然后与本地的端口进行绑定,接着就开始接收客户端的请求并建立与它的连接,接下来,客户端发送的消息。

tcpserver.c代码:

int main()
{
	struct sockaddr_in server_sockaddr,client_sockaddr;
	int sin_size,recvbytes;
	int sockfd, client_fd;
	char buf[BUFFER_SIZE];

	/* 建立socket连接 */
	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
	{
		perror("socket");
		exit(1);
	}

	printf("Socket id = %d\n",sockfd);

	/* 设置socket_in 结构体中相关的参数 */
	server_sockaddr.sin_family = AF_INET;               /* ipv4的协议 */
	server_sockaddr.sin_port = htons(PORT);             /* 设置端口 */
	server_sockaddr.sin_addr.s_addr = INADDR_ANY;       /* ip地址服务器这边的地址 */
	bzero(&(server_sockaddr.sin_zero),8);               /* 保持位数 */

	int i = 1; 				/* 允许重复使用本地地址与套接字进行绑定 */
	setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, &i,sizeof(i));

	/* 绑定函数bind() */
	if(bind(sockfd,(struct sockaddr *)&server_sockaddr,sizeof(struct sockaddr))== -1)
	{
		perror("bind");
		exit(1);
	}

	printf("bind success!\n");

	/* 调用listen()函数,创建未处理请求的队列 */
	if( listen(sockfd, MAX_QUE_CONN_NM) == -1)
	{
		perror("listen");
		exit(1);
	}
	printf("Listening....\n");

	/* 调用accept()function,waiting client connnectting */
	if((client_fd = accept(sockfd, (struct sockaddr *) & client_sockaddr,&sin_size)) == -1)
	{
		perror("accept");
		exit(1);
	}

	memset(buf,0,sizeof(buf));

	if((recvbytes = recv(client_fd,buf,BUFFER_SIZE,0)) == -1)
	{
		perror("recv");
		exit(1);
	}

	printf("Received a message :%s\n",buf);
	close(sockfd);
	exit(0);
}

客户端的程序:

#include "myinclude.h"
int main(int argc, char *argv[])
{
	int sockfd,sendbytes;
	char buf[BUFFER_SIZE];
	struct hostent *host;
	struct sockaddr_in serv_adr;

	if(argc < 3)
	{
		fprintf(stderr,"USAGE:./client Hostname(or ipaddress)Text\n ");
		exit(1);
	}
/* address resolution function */
	if((host = gethostbyname(argv[1])) == NULL)
	{
		perror("gethostbyname");
		exit(1);
	}

	memset(buf,0,sizeof(buf));
	sprintf(buf,"%s",argv[2]);
/* create socket */
	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
	{
		perror("socket");
		exit(1);
	}
/* set up the structure-related parameters of sockaddr_in */
	serv_adr.sin_family = AF_INET;
	serv_adr.sin_port = htons(PORT);
	serv_adr.sin_addr = *((struct in_addr *)host->h_addr);
	bzero(&(serv_adr.sin_zero),8);
/* call connect function Initiate a connection to the server */
	if(connect(sockfd,(struct sockaddr *)&serv_adr,sizeof(struct sockaddr)) == -1)
	{
		perror("connect");	
		exit(1);
	}
/* send messages to server */
	if((sendbytes = send(sockfd,buf,strlen(buf),0))==-1)
	{
		perror("Send");
		exit(1);
	}

	close(sockfd);
	exit(0);
}
验证程序 
技术分享

技术分享

技术分享

技术分享


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。