0

这是客户端框架。其中是“hello server”行。我想在服务器框架中显示“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();
    }
4

1 回答 1

2

在客户端程序中,您使用了端口 1167...但是在服务器中,您尝试从端口 7070 接收...所以使两个端口相同(例如 7070)以接收消息...。

于 2013-10-19T01:51:15.997 回答