简体   繁体   English

从服务器udp访问数据

[英]access data from server udp

I have a problem, I have a client server udp, in server side I need to access data from client side to control movement of the robot. 我有一个问题,我有一个客户端服务器udp,在服务器端,我需要从客户端访问数据以控制机器人的移动。 For the experiment I use to print "oke" if the value of the data is 1. here the code program: 对于实验,如果数据值为1.,我将使用“ oke”打印代码,此处为代码程序:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <errno.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 
#include <netdb.h>
#define MYPORT 4950
#define MAXBUFLEN 100
int sockfd;
struct sockaddr_in my_addr; 
struct sockaddr_in their_addr; 
struct hostent *he;
int addr_len, numbytes;
char dt[30];
char buf[MAXBUFLEN];
int main() 
{
printf("‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐\n");

if((sockfd=socket(AF_INET,SOCK_DGRAM,0))==-1){
    perror("socket");
    exit(1); }

my_addr.sin_family = AF_INET; 
my_addr.sin_port = htons(MYPORT); 
my_addr.sin_addr.s_addr = INADDR_ANY; 
memset(&(my_addr.sin_zero),'\0',8);

if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1){
    perror("bind");
    exit(1); }


while(1){
    addr_len = sizeof(struct sockaddr);
    if((numbytes=recvfrom(sockfd,buf,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,&addr_len))==-1)
    {
        perror("recvfrom");
        exit(1);}

    buf[numbytes]='\0';
    printf("%s : \"%s\"\n", inet_ntoa(their_addr.sin_addr), buf);

    if (buf[0]==1)
    { printf("oke\n");}

    printf("Me : ");
    scanf("%s", dt); 
    if((numbytes=sendto(sockfd,dt,strlen(dt),0,(struct sockaddr*)&their_addr,sizeof(struct sockaddr)))==-1)
    {
        perror("sendto");
        exit(1); 
    }

}
close(sockfd);
return 0;
}

when I put "1" in client side the result is: 当我在客户端输入“ 1”时,结果是:

 ‐‐‐‐‐ PROGRAM CHATTING ‐‐‐‐‐
 130.130.66.76 : "1"
 Me :

even in the program there are: 即使在程序中也有:

if (buf[0]==1)
{ printf("oke\n");}

why the program cannot access to inside of if? 为什么程序无法访问if?

Try if (buf[0]=='1') 尝试if (buf[0]=='1')

Number characters map to different ASCII values than their number, so, for example, '1'==49 . 数字字符映射到与其数字不同的ASCII值,例如, '1'==49

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM