简体   繁体   English

使用套接字将int从Java发送到C

[英]Sending an int from Java to C using sockets

I was just wondering how to send an int from a Java application to a C application using sockets. 我只是想知道如何使用套接字从Java应用程序向C应用程序发送int。 I have got different C programs communicating with each other and have got the Java application retrieving data from the C application, but I can't work out sending. 我有不同的C程序相互通信,并且Java应用程序从C应用程序检索数据,但是我无法解决发送问题。

The C application is acting as database, the Java application then sends a user id (a 4 digit number) to the C application, if it exists it returns that record's details. C应用程序充当数据库,然后Java应用程序将用户ID(4位数字)发送给C应用程序(如果存在),它将返回该记录的详细信息。

In Java I have tried using a printWriter and DataOutputStream to send the data, printWriter produces weird symbols and DataOutputStream produces "prof_agent.so". 在Java中,我尝试使用printWriter和DataOutputStream发送数据,printWriter产生奇怪的符号,DataOutputStream产生“ prof_agent.so”。

Any help would be appreciated as I don't have a good grasp of sockets at the moment. 任何帮助将不胜感激,因为我目前不掌握套接字。

You can use DataOutputStream.writeInt . 您可以使用DataOutputStream.writeInt It writes an int already in network byte order by contract. 它已按合同以网络字节顺序写入一个int。

On a C side you can call recv , or read to fill in the 4-byte buffer, and then you can use ntohl ( Network-TO-Host-Long ) to convert the value you've just read to your platform int representation. C端,您可以调用recvread以填充4字节的缓冲区,然后可以使用ntohl (Network-TO-Host-Long)将刚刚读取的值转换为平台int表示形式。

You can send the textual representation. 您可以发送文本表示。 So the number 123 would be sent as 3 bytes '1' '2' '3'. 因此,数字123将作为3个字节“ 1”,“ 2”,“ 3”发送。

It's a bit too late but let this answer be here. 为时已晚,但是让这个答案在这里。 Using UDP sockets: 使用UDP套接字:

Java code: Java代码:

public void runJavaSocket() {
            System.out.println("Java Sockets Program has started."); int i=0;    
    try {
            DatagramSocket socket = new DatagramSocket();
            System.out.println("Sending the udp socket...");
            // Send the Message "HI"
            socket.send(toDatagram("HI",InetAddress.getByName("127.0.0.1"),3800));
            while (true)
            {
              System.out.println("Sending hi " + i);
              Thread.currentThread();
              Thread.sleep(1000);
              socket.send(toDatagram("HI " +             String.valueOf(i),InetAddress.getByName("127.0.0.1"),3800));
                    i++;
            }
        } 
    catch (Exception e) 
    {
         e.printStackTrace();
    }
}

public DatagramPacket toDatagram(
          String s, InetAddress destIA, int destPort) {
    // Deprecated in Java 1.1, but it works:
    byte[] buf = new byte[s.length() + 1];
    s.getBytes(0, s.length(), buf, 0);
    // The correct Java 1.1 approach, but it's
    // Broken (it truncates the String):
    // byte[] buf = s.getBytes();
    return new DatagramPacket(buf, buf.length, 
    destIA, destPort);
    }

C# code: C#代码:

        string returnData;
        byte[] receiveBytes;
        //ConsoleKeyInfo cki = new ConsoleKeyInfo();

        using (UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800)))
        {
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3800);
            while (true)
            {
                receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
                returnData = Encoding.ASCII.GetString(receiveBytes);
                Console.WriteLine(returnData);
            }
        }

Try this: 尝试这个:

Socket s = ...;
DataOutputStream out = null;
try {
    out = new DataOutputStream( s.getOutputStream() );
    out.writeInt( 123456 );
} catch ( IOException e ) {
    // TODO Handle exception
} finally {
    if ( out != null ) {
        try {
            out.close();
        } catch ( IOException e ) {
            // TODO Handle exception
        }
    }
}

It whould help if you could explain a little more what your problem is. 如果您可以多解释一些问题,它将对您有所帮助。

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

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