我从互联网上的某些来源获取代码,现在是:
服务器端:
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
serverSocket.setBroadcast(true);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
serverSocket.receive(receivePacket);
//System.out.println(serverSocket.getAddress().getHostAddress());
System.out.println(receivePacket.getAddress().getHostAddress()+" is connected");
String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("RECEIVED: " + sentence +" from: "+receivePacket.getAddress().getHostAddress());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
System.out.println("Port: "+port);
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, port); //
serverSocket.send(sendPacket);
}
}
}
Client1方:
import java.io.*;
import java.net.*;
class Client1 {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setBroadcast(true);
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
Boolean status = true;
while(status){
String sentence = "";
sentence = inFromUser.readLine();
if(sentence.equals("exit")){
break;
}
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("FROM SERVER:" + modifiedSentence);
}
clientSocket.close();
}
}
Client2 Side:与Client1相同。
我的问题是:
提前谢谢