这是客户端框架。其中是“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();
}