我如何收到数据报包

时间:2013-10-19 01:39:36

标签: java datagram

这是客户端框架。在它是“你好服务器”行。我想在服务器框架中显示“hello server”。我到目前为止的代码是我从我的教科书中记住的。我不记得其余的。

package datagrams;
import java.io.*;
import java.net.*;

public class Client extends javax.swing.JFrame implements Runnable {


    public Client() {
        initComponents();
    }


    @Override
    public void run(){

        DatagramSocket socket = null;
        DatagramPacket recvPacket, sendPacket;
        this.setVisible(true);
        try {
            socket = new DatagramSocket();
            InetAddress  hostAddress = InetAddress.getByName("localhost");
            String userString = "hello server";
            byte sendbuf[] = userString.getBytes();
            sendPacket = new DatagramPacket(sendbuf, sendbuf.length, hostAddress, 1167);
            socket.send(sendPacket);
            recvPacket = new DatagramPacket(new byte[512], 512);
            socket.receive(recvPacket);


        catch(Exception ioe){


        }
        socket.close();

            }

和服务器框架

package datagrams;

import java.io.*;
import java.net.*;

public class Server extends javax.swing.JFrame implements Runnable {

    static int  PORT = 7070;

    public Server() {
        initComponents();

    }

    @Override public void run(){
        DatagramSocket socket = null;
        DatagramPacket recvPacket, sendPacket;
        this.setVisible(true);
        try{
            socket = new DatagramSocket(PORT);
            while (socket != null){
                recvPacket = new DatagramPacket(new byte[512], 512);
                socket.receive(recvPacket);
                sendPacket = new DatagramPacket(recvPacket.getData(), recvPacket.getLength(), recvPacket.getAddress(), recvPacket.getPort());
                socket.send(sendPacket);
            }

        }
    catch(IOException e){
        System.out.println(e.toString());
    }

    socket.close();
    }

1 个答案:

答案 0 :(得分:2)

在客户端程序中,您使用了端口1167 ...但是在服务器中,您尝试从端口7070接收....因此,使端口相同(例如7070)以接收消息.... / p>