C服务器和Java客户端之间的UDP连接 [英] UDP connection between C server and Java client

查看:92
本文介绍了C服务器和Java客户端之间的UDP连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还有一个问题:)我在C中有一个简单的UDP服务器,它读取一些字节,并对这些字节应用一些解码,并且当它具有形式为### @ #### @ ### @#的STRING时##他通过UDP将其发送到C中的另一台服务器。这是我的C服务器的代码,称为preprocesamiento.c。我张贴整个cos较为容易,但这也许与我的问题无关。

I have another question :) I have a simple UDP server in C that reads some bytes applies some decode to those bytes and when it has a STRING of the form ###@####@###@### he sends it throug UDP to another server in C. Here is the code for my C server that is called preprocesamiento.c Im posting the whole thing cos is easyer but maybe this has nothing to do with my problem.

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <stdint.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#define MAXBUF 512
#define SENDING 0x52
#define RESIVING 0xB4
#define TYPE 0xA3F0

int createSocket();
char *unbase64(unsigned char *input, int length);
/* This function recives bytes(ASCII numbers) and returns the char */
void cambiarAChars(char* bytes, char* result)

  {

unsigned int ch;

    char a[4];
    char buff[50];
    strcpy(result,"");
    int i=0;
    while(i<strlen(bytes))
    {
      if(bytes[i]=='1')
       {

    a[0]=bytes[i];
    a[1]=bytes[i+1];
    a[2]=bytes[i+2];
    a[3]='\0';
    i=i+3;
   }
else

{
    a[0]=bytes[i];
    a[1]=bytes[i+1];
    a[2]='\0';
    i=i+2;
}
ch = atoi(a);
sprintf(buff,"%c",ch);
strcat(result,buff);
    }
 }
 /*this is the message that is going to be sent to the other server*/
char msg[MAXBUF];
 /*this is the bytes recived*/
char bytes[MAXBUF];
void loadConfig(struct sockaddr_in *udpServer,struct sockaddr_in *thisServer,unsigned char *file);

 int sendDataToServerXX(struct sockaddr_in *udpServer, int udpSocket);
 int *useStdrr;
 int *maxRequests;
 int returnStatus;

 int main(int argc, char* argv[])
 {
 if (argc < 2)
     {
       fprintf(stderr, "Usage: %s <file.config adress>\n", argv[0]);
       exit(1);

     }
useStdrr=malloc(sizeof(int));
maxRequests=malloc(sizeof(int));
    struct sockaddr_in  udpServer,thisServer,udpClient;
    loadConfig(&udpServer,&thisServer, argv[1]);
    int thisServerSocket = createSocket();
    int udpSocket=createSocket();
int addrlen;


printf("Listening on.. %d \n",thisServer.sin_port);



thisServer.sin_family = AF_INET;

returnStatus = bind(thisServerSocket, (struct sockaddr*)&thisServer, sizeof(thisServer));



if (returnStatus == 0) {



    fprintf(stderr, "Bind completed!\n");



 } 

 else {



    fprintf(stderr, "Could not bind to address \n" );





    close(thisServerSocket);

    exit(1);

  }



/*En este while infinito estamos esperando los datos de las tramas*/

while (1)
   {





    addrlen = sizeof(udpClient);

    /* How to resive a struct? */

    returnStatus = recvfrom(thisServerSocket,(char*)&bytes, sizeof(bytes), 0, 

                            (struct sockaddr*)&udpClient, &addrlen);



        if (returnStatus == -1) {



                fprintf(stderr, "Could not receive message!\n");





        } 





        else {



        printf("Lo que llego: %s \n",bytes);

        /*Primero quitamos el 0 y 1 y guardamos el nuevo arreglo en p*/



        bytes[strlen(bytes)-1]='\0';



        char  p[strlen(bytes)];

        int i=0;

        while(bytes[i+1]!='\0'){



            p[i]=bytes[i+1];

            i++;

        }





        /*esto simula la cambiada a base10 de base64*/

        char *result=malloc(512);

        char *p2=malloc(sizeof(p)+1);

        strcpy(p2,p);

        cambiarAChars(p2,result);



        strcat(result,"\n\0");

        printf("TAMANO: %d \n",strlen(result));

        char *output = unbase64(result, strlen(result));

        printf("Unbase64: %s\n", output);



        msg[0]='%';

        strcat(msg,output);
        int f=strlen(msg);
        msg[f]='%';
        msg[f+1]='\0';

        printf("Voy a mandar: %s \n",msg);

        sendDataToServerXX(&udpServer,udpSocket);

        free(output);




        }







}



close(thisServerSocket);

    close(udpSocket);

 }



 int createSocket()

 {

 /* create a socket */

int Socket;

  Socket = socket(AF_INET, SOCK_DGRAM, 0);



  if (Socket == -1)

  {

    if(*useStdrr)

        {

    fprintf(stderr, "Could not create a socket!\n");

    }

    exit(1);

  }

  else {

    printf("Socket created.\n");

   }

return Socket;

 }



 void loadConfig(struct sockaddr_in *udpServer,struct sockaddr_in *thisServer, unsigned char *file)

{

 char line[256];

 int linenum=0;

  FILE* f = fopen(file, "r");

while(fgets(line, 256, f) != NULL)

{

    char atribute[256], value[256];



    linenum++;

    if(line[0] == '#'||line[0] == ' ') {

    continue;

    }

    else{

    if(sscanf(line, "%s %s", atribute, value) != 2)

    {

            fprintf(stderr, "Syntax error, line %d\n", linenum);

            continue;

    }



    if(!strcmp(atribute,"server_address" ))

    {

        if(!strcmp(value,""))

        {

        udpServer->sin_addr.s_addr = htonl(INADDR_ANY);

        }

        else{

        udpServer->sin_addr.s_addr = inet_addr(value);

        }

    }

    else if(!strcmp(atribute,"server_port"))

    {

        udpServer->sin_port = htons(atoi(value));

    }

    else if(!strcmp(atribute,"print_message_details"))

    {

        if(!strcmp(value,"ON"))

        {

            *useStdrr=1;

        }

        else

        {

            *useStdrr=0;

        }

    }

    else if(!strcmp(atribute,"request_count"))

    {

        *maxRequests=5;

    }



    else if(!strcmp(atribute,"valor_que_viene_del_cohete_simulado"))

    {







    }



    else if(!strcmp(atribute,"this_server_address"))

    {

        if(!strcmp(value,""))

        {

            thisServer->sin_addr.s_addr = htonl(INADDR_ANY);

        }

        else{

            thisServer->sin_addr.s_addr = inet_addr(value);

        }

    }

    else if(!strcmp(atribute,"this_server_port"))

    {

        thisServer->sin_port = htons(atoi(value));



    }

}



}

 }



  int sendDataToServerXX(struct sockaddr_in *udpServer, int udpSocket)

  {
   udpServer->sin_family = AF_INET;

int in=0;

int boolv=0;



while(in<*maxRequests)

{

    in++;



    returnStatus = sendto(udpSocket,(char*) &msg, sizeof(msg), 0, 

                      (struct sockaddr*)udpServer, sizeof(*udpServer));



    if (returnStatus == -1) {

        if(*useStdrr)

        {

        fprintf(stderr, "Could not send message!\n");



        }

    }

    else {





        printf("Datos enviados al servidor xx.\n");

            memset(msg, 0, strlen(msg));

        in=*maxRequests;

        boolv=1;



  }

}

if(!boolv)

{

    if(*useStdrr)

    {

    fprintf(stderr, "fixed number of requests finished.. no reply.\n");

    }

}

 return 0;
 }


 char *unbase64(unsigned char *input, int length)

 {

  BIO *b64, *bmem;
  char *buffer = (char *)malloc(length);

  memset(buffer, 0, length);



  b64 = BIO_new(BIO_f_base64());

  BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);

   bmem = BIO_new_mem_buf(input, length);

   bmem = BIO_push(b64, bmem);

   BIO_read(bmem, buffer, length);
   BIO_free_all(bmem);



 return buffer;

 }

好,所以我做了一个模拟器,可以将数据发送到该服务器...基本上是一个UDP客户端,可以发送我想要的字节。连接和整个过程都很好:)。现在,我正在尝试连接到真正的测试仪,这是一个Java jar,可以根据服务器的要求通过UDP发送数据。唯一的问题是我没有Java源代码,因为它不是我的。。。但是程序似乎运行得很顺利(Java jar),但是当我检查服务器时,没有收到连接。是的,我在正确的端口中等待,并且C和Java的两个程序都在同一台机器(UBUNTU)上运行。

Ok so i made a simulator that sends data to this server... basically a UDP client that sends bytes as i want them. And the connection and the whole thing works very nice :). Now im trying to connect to the real tester, which is a java jar that sends data as my server wants it through UDP. The only problem is that i dont have the java source code, because its not mine... But the program seems to run smoothly (the java jar) But when i check my server no connections where recived. And yeah im waiting in the right port and both programs the C and Java are running in the same machine (UBUNTU).

我发布了用C制成的客户端模拟器

I post my client simulator made in C that works very nice with this server.

对不起,我从配置文件中加载了很长的cos:

Sorry its a bit long cos i load from a config file:

 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netdb.h>
  #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <time.h>
 #include <string.h>
#define MAXBUF 1024
#define SENDING 0x52
#define RESIVING 0xB4
 #define TYPE 0xA3F0

int createSocket();


char msg[MAXBUF];





 void loadConfig(struct sockaddr_in *udpServer, char *file);

  int *useStdrr;

  int *maxRequests;

  int *timeOut;



  int main(int argc, char* argv[])

 {

   int returnStatus;

   int addrlen;

   struct sockaddr_in udpClient, udpServer;

   char buf[MAXBUF]; 

useStdrr=malloc(sizeof(int));

maxRequests=malloc(sizeof(int));

timeOut=malloc(sizeof(int));

/*ms.timezone="AES";*/



   if (argc < 2)

   {    

       fprintf(stderr, "Usage: %s <file.config adress>\n", argv[0]);


    exit(1);

  }



int udpSocket=createSocket();

   udpServer.sin_family = AF_INET;


loadConfig(&udpServer, argv[1]);



/*how to send a struct here?*/

int in=0;

int boolv=0;

printf("Request number %i\n",*maxRequests);

while(in<*maxRequests)

{

    in++;

    printf("Request number %i\n",in);





    printf("Adresss::: %d\n",udpServer.sin_addr.s_addr);

    printf("PORT:::: %i\n",udpServer.sin_port);



    returnStatus = sendto(udpSocket,(char*) &msg, sizeof(msg), 0, 

                      (struct sockaddr*)&udpServer, sizeof(udpServer));



    if (returnStatus == -1) {

        if(*useStdrr)

        {

        fprintf(stderr, "Could not send message!\n");



        }

    }

    else {



    printf("Message sent.\n");



    /* message sent: look for confirmation */

/*

    addrlen = sizeof(udpServer);



    returnStatus = recvfrom(udpSocket, (char*) &msg, sizeof(msg), 0, 

                            (struct sockaddr*)&udpServer, &addrlen);



    if (returnStatus == -1) {

        if(*useStdrr)

        {

        fprintf(stderr, "Did not receive confirmation!\n");

        }

    }





    else {



        printf("Second: %s\n", msg);





        */

        in=*maxRequests;

        boolv=1;

        /*







    }*/



  }

}

if(!boolv)

{

    if(*useStdrr)

    {

    fprintf(stderr, "fixed number of requests finished.. no reply.\n");

    }

}





 close(udpSocket);

 return 0;



 }



 int createSocket()

 {

 /* create a socket */

int Socket;

 Socket = socket(AF_INET, SOCK_DGRAM, 0);



 if (Socket == -1)

 {

    if(*useStdrr)

        {

    fprintf(stderr, "Could not create a socket!\n");

    }

    exit(1);

 }

 else {

    printf("Socket created.\n");

 }

return Socket;

 }



  void loadConfig(struct sockaddr_in *udpServer, char *file)

  {

   char line[256];

    int linenum=0;




    FILE* f = fopen(file, "r");

while(fgets(line, 256, f) != NULL)

{

    char atribute[256], value[256];



    linenum++;

    if(line[0] == '#'||line[0] == ' ') {

    continue;

    }

    else{

    if(sscanf(line, "%s %s", atribute, value) != 2)

    {

            fprintf(stderr, "Syntax error, line %d\n", linenum);

            continue;

    }

    printf("Atribute: %s\n",atribute);

    printf("Value: %s\n",value);

    if(!strcmp(atribute,"server_address" ))

    {

        if(!strcmp(value,""))

        {

        udpServer->sin_addr.s_addr = htonl(INADDR_ANY);

        }

        else{

        udpServer->sin_addr.s_addr = inet_addr(value);

        }

    }

    else if(!strcmp(atribute,"server_port"))

    {

        udpServer->sin_port = htons(atoi(value));

    }

    else if(!strcmp(atribute,"print_message_details"))

    {

        if(!strcmp(value,"ON"))

        {

            *useStdrr=1;

        }

        else

        {

            *useStdrr=0;

        }

    }

    else if(!strcmp(atribute,"request_count"))

    {

        *maxRequests=atoi(value);

    }

    else if(!strcmp(atribute,"request_*timeOut"))

    {

        *timeOut=atoi(value);

    }


}



}

 }

现在真正的问题:我是否需要做一些不同的事情才能将Java客户端从C连接到C服务器比我做什么来连接到另一个C客户端?如果答案是否定的,那么问题出在Java项目中?他们告诉我它的工作正常,但我认为他们已经用JAVA服务器对其进行了测试。是否有区别?如果问题出在Java项目中,我应该告诉他们进行更改以使其与我的C服务器一起工作吗?

Now the real QUESTION: Do i have to do something different to connect froma java client to a C from the C server than what i do to connect to another C client? If the answer is no then the problem is in the java project? they tell me its working fine but I think they have tested it with a JAVA server.. Is there any diference? If the problem is in the java project what should i tell them to change for it to work with my C server?

很多!!!!!!

亚历杭德罗·卡萨斯

推荐答案

没有UDP连接之类的东西。在UDP中,程序仅将给定IP上给定端口的数据包扔掉。如果在该IP /端口上没有监听的内容,或者接收程序决定忽略UDP数据包,则会将其丢弃。

There is no such thing as a UDP connection. In UDP, a program just tosses packets at a given port at a given IP. If there is nothing listening at that IP/port, or the receiving program decides to ignore the UDP packets, it gets dropped. If you want an actual connection, you would use TCP.

此外,某些ISP默认会阻止某些类型的UDP数据包。

In addition, some ISP block some types of UDP packets by default

在Java中,TCP套接字称为Socket,而UDP套接字称为DatagramSocket。确保您是从Java客户端上的DatagramSocket发送的。

In Java, a TCP socket is called a Socket and a UDP socket is called a DatagramSocket. Make sure you are sending from a DatagramSocket on your Java client.

我还没有用C完成套接字编程。

I haven't done socket programming in C though.

最后,如果您发布了一些Java代码,将会有所帮助。

Finally, it would help if you posted some of your Java code.

这篇关于C服务器和Java客户端之间的UDP连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆