我目前正在编写两个java类(客户端和服务器)。客户端从键盘输入数字并将其发送到服务器。然后,服务器将此数字乘以2并将其发送回客户端。这些数字也应该一路打印到屏幕上,例如,如果我输入数字3,我应该
"来自客户:3" "来自服务器:6"
除非客户端收到负数,否则他们应该继续这样做,例如将数字-3发送到服务器并返回-6。
到目前为止,我对这两个类的代码是:
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.Scanner;
class Client {
public static void main(String args[]) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket();
System.out.println("Insert number: ");
Scanner s= new Scanner(System.in);
int num = s.nextInt();
byte[] sendData = ByteBuffer.allocate(4).putInt(num).array();
InetAddress IPAddress = InetAddress.getByName("localhost");
int port = 1999;
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length , IPAddress ,1999);
clientSocket.send(sendPacket);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
byte[] receiveData = new byte[4];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
int numberReceived = ByteBuffer.wrap(receivePacket.getData()).getInt();
System.out.println("FROM SERVER:" + numberReceived);
clientSocket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
class Server {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(1999);
while(true)
{
byte[] receiveData = new byte[4];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
int num = ByteBuffer.wrap(receivePacket.getData()).getInt();
System.out.println("FROM Client:" + num);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
int numtosend = num * 2;
byte[] sendData = ByteBuffer.allocate(4).putInt(numtosend).array();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,port);
serverSocket.send(sendPacket);
}
}
}
目前,当我运行程序时,我得到的是输入的数字。
谁能告诉我哪里出错了?
非常感谢提前:)
答案 0 :(得分:0)
你出错的地方是你还没有完成这个程序。
您的客户只读取一个号码,发送一个号码,接收一个回复。
你需要一个循环。
您还需要实现关于停止否定号码的部分。