linux TCP通讯代码 验证OK

嵌入式Linux实现TCP/IP通信

实现client向server发送数据。

server里面的rev要用nsockfd

client里面的send用sockfd

tcp_server代码:

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

#define PORT 8088 // The port which is communicate with server
#define BACKLOG 10

#define LENGTH 512 // Buffer length
int main ()
{
int iR;
int sockfd; // Socket file descriptor
int nsockfd; // New Socket file descriptor
int num;
int sin_size; // to store struct size
char sdbuf[LENGTH]; // Send buffer
char revbuf[LENGTH]; // Receive buffer
struct sockaddr_in addr_local;
struct sockaddr_in addr_remote;
// char sendstr[16]= {“123456789 abcde”};

	/* Get the Socket file descriptor */  
	if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 )  
	{   
    	printf ("ERROR: Failed to obtain Socket Despcritor.\n");
    	return (0);
	} else {
    	printf ("OK: Obtain Socket Despcritor sucessfully.\n");
	}

	/* Fill the local socket address struct */
	addr_local.sin_family = AF_INET;           	// Protocol Family
	addr_local.sin_port = htons (PORT);         	// Port number
	addr_local.sin_addr.s_addr  = htonl (INADDR_ANY);  // AutoFill local address
	memset (addr_local.sin_zero,0,8);          		// Flush the rest of struct

	/*  Blind a special Port */
	if( bind(sockfd, (struct sockaddr*)&addr_local, sizeof(struct sockaddr)) == -1 )
	{  
	  	printf ("ERROR: Failed to bind Port %d.\n",PORT);
    	return (0);
	} else {
    	printf("OK: Bind the Port %d sucessfully.\n",PORT);
	}

	/*  Listen remote connect/calling */
	if(listen(sockfd,BACKLOG) == -1)    
	{  
    	printf ("ERROR: Failed to listen Port %d.\n", PORT);
    	return (0);
	} else {
    	printf ("OK: Listening the Port %d sucessfully.\n", PORT);
	}

	while(1)
	{  
    	sin_size = sizeof(struct sockaddr_in);  
    
    	/*  Wait a connection, and obtain a new socket file despriptor for single connection */
    	if ((nsockfd = accept(sockfd, (struct sockaddr *)&addr_remote, (socklen_t *__restrict)&sin_size)) == -1)
    	{  
        	printf ("ERROR: Obtain new Socket Despcritor error.\n");
        	continue;
    	} else {
        	printf ("OK: Server has got connect from %s.\n", inet_ntoa(addr_remote.sin_addr)); 
    	}
    
	
    	/* Child process */
    	if(!fork())                    
    	{  
        	
        	    while (strcmp(revbuf,"exit") != 0)
        	    { 
				//接收数据
				memset (revbuf,0,LENGTH);
				
				if((num = recv(nsockfd, revbuf, LENGTH, 0))>0)
				{
					printf ("OK: Receviced numbytes = %d\n", num);
					revbuf[num] = '\0';
					printf ("OK: Receviced string is: %s\n", revbuf);
				}
				
				
        	    }
     	}  
		
     	close(nsockfd);  
     	while(waitpid(-1, NULL, WNOHANG) > 0);   

 }    

}

tcp_client代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#define PORT 8088 // The port which is communicate with server
#define LENGTH 256 // Buffer length

int main(int argc, char *argv[])
{
int iR; //
int nsockfd; // New Socket file descriptor
int sockfd; // Socket file descriptor
int num; // Counter of received bytes
char revbuf[LENGTH]; // Receive buffer
char sdbuf[LENGTH]; // Send buffer
struct sockaddr_in remote_addr; // Host address information

	/* Check parameters number */
	if (argc != 2)                     
	{    
    	printf ("Usage: client HOST IP (ex: ./client 192.168.7.239).\n");
    	return (0);
	}

	/* Get the Socket file descriptor */
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
    	printf("ERROR: Failed to obtain Socket Descriptor!\n");
    	return (0);
	}

	/* Fill the socket address struct */
	remote_addr.sin_family = AF_INET;              	// Protocol Family
	remote_addr.sin_port = htons(PORT);           		// Port number
	inet_pton(AF_INET, argv[1], &remote_addr.sin_addr); 	// Net Address
	memset (remote_addr.sin_zero,0,8);                 	// Flush the rest of struct

	/* Try to connect the remote */
	if (nsockfd=connect(sockfd, (struct sockaddr *)&remote_addr,  sizeof(struct sockaddr)) == -1) 
	{
    	printf ("ERROR: Failed to connect to the host!\n");
    	return (0);
	} else {
    	printf ("OK: Have connected to the %s\n",argv[1]);
	}

	
    
		/* Try to connect the server */
		printf("You can enter string to send, and press 'exit' to end the connect.\n");
		 
		while(strcmp(sdbuf,"exit") != 0)
		{      
			
			/* 发送数据------------ */
			iR=(int)scanf("%s",sdbuf);
			if(iR>512)break;
			if((num=send(sockfd,sdbuf,strlen(sdbuf),0))==-1)
			{
				printf("ERROR:Fail to send string\n");
				close(nsockfd);
				exit(1);
			}
			printf("OK:Sent %d bytes sucessful,please enter again.\n",num);
		}
		
	
	
	printf("Exit connect,Byebye!\n");
	close (sockfd);
	return (0);

}

开发板上执行tcp_client,主机上执行tcp_server
在Linux系统上编译tcp_client指令:arm-none-linux-gnueabi-gcc tcp_client.c -o client

编译tcp_server指令:gcc tcp_server.c -o tcp_server

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可芯智能科技研究院

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值