开发者

Sending Java Packets to Python Server?

I'm just starting to learn about sending UDP packets, and I'm running into a problem. I've written a Java client and server which easily communicate with each other, and I've done a Python client/server combo, but I'm not sure how to send a UDP packet from Java and receive it in Python. Here's what I have for the Java client:

import java.i开发者_JAVA百科o.*;
import java.net.*;

public class testclient {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket();

        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(buf, buf.length, address, Integer.parseInt(args[0]));

        System.out.println("Sending...");
        socket.send(packet);

        System.out.println("Receiving...");
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);

        String received = new String(packet.getData(), 0, packet.getLength());
        System.out.println(received);
        System.out.println("Done!");

        socket.close();
    }
}

And the Python server:

from sys import *
from socket import *

host = gethostname()
port = int(argv[1])
address = (host, port)

print "Binding..."
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(address)

print "Receiving..."
data, client = sock.recvfrom(256)

print "Sending to", client
sock.sendto("Hi", client)

print "Closing..."
sock.close()

print "Done!"

All I'm trying to do here is send a request from the Java client to the Python server, then have the Python server send "Hi" back to the Java client, and have the client print the string. What happens for me is the client sends the packet, and the server waits at the sock.recvfrom(256) and never receives the packet (or that's what it looks like anyway).

Any ideas? I'm guessing it's some difference between how Java and Python handle the packets but, I'm not sure.

EDIT: Just for clarification, the port number is passed in via command-line arguments for both of these applications.


The problem must be within your code, they should be able to communicate: this is a good example of writing a client server pair in java.


So, to start, I'm on Ubuntu 10.10.

I went into /etc/hosts and it looks like 127.0.0.1 was assigned to localhost.localdomain, while 127.0.1.1 was assigned to my machine's name. So, Python was using the localhost address, while Java was using my machine name address. I changed localhost to my machine name and everything works now.

Thanks everybody for trying to help!


In Java, I see where you create the packet, but I don't see you actually putting any data into the packet using setData before sending it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜