如何使用数据报套接字执行双向IPC

时间:2015-07-19 11:27:36

标签: java sockets networking udp ipc

我开发了一个应用程序,它使用两个应用程序内程序(进程)之间的双向通信。我故意使用DatagramSocket是有原因的。在应用程序的服务器端,当我发送DatagramPacket时,它不是由客户端接收而是由服务器本身接收,因为服务器在它发送之后接收消息。这是因为客户端和服务器具有相同的主机地址。如果客户端和服务器程序在不同的计算机上运行,​​则不会发生此问题。客户端和服务器程序是:

ServerProgram:

all: {
  files: examples.cli.files.concat(examples.srv.files)
}

客户计划:

package Sockets;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

class ServerTask extends Thread {
    private DatagramSocket serverSocket;
    private final int portNumber;

    public ServerTask() throws SocketException {
        portNumber = 1234;
        serverSocket = new DatagramSocket(portNumber);

    }

    @Override
    public void run() {
        while (true){
            byte[] byteBuffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(byteBuffer, byteBuffer.length);
            try {
                serverSocket.receive(packet);
                InetAddress clientAddress = packet.getAddress();
                DatagramPacket packet2 = new DatagramPacket("Hi client".getBytes(),
                        "Hi client".getBytes().length,
                        clientAddress,
                        3444);
                serverSocket.send(packet2);
                Thread.sleep(100);

                System.out.printf("Server received: %s\n", new String(byteBuffer));
            } catch (IOException e) {
                System.err.println("IOException!");
                System.exit(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

public class UDPEchoServer {
    public static void main(String[] args) throws SocketException{
        ServerTask myServerTask = new ServerTask();
        myServerTask.start();
    }

}

0 个答案:

没有答案