我试图连接来自不同计算机的多个客户端并使用UDP向对方发送消息,但这只适用于本地!任何人都可以指出我为什么不在其他电脑上工作?
PS:我尝试在其他计算机上运行客户端并将我的IP地址作为主机,但它仍然无效。
这是我的 Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws Exception {
// The default port
int clientport = 4000;
String host = "localhost";
if (args.length < 1) {
System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport);
}
// Get the port number to use from the command line
else {
//host = args[0];
clientport = Integer.valueOf(args[0]).intValue();
System.out.println("Usage: UDPClient " + "Now using host = " + host + ", Port# = " + clientport);
}
// Get the IP address of the local machine - we will use this as the address to send the data to
InetAddress ia = InetAddress.getByName(host);
SenderThread sender = new SenderThread(ia, clientport);
sender.start();
ReceiverThread receiver = new ReceiverThread(sender.getSocket());
receiver.start();
}
}
class SenderThread extends Thread {
private InetAddress serverIPAddress;
private DatagramSocket udpClientSocket;
private boolean stopped = false;
private int serverport;
public SenderThread(InetAddress address, int serverport) throws SocketException {
this.serverIPAddress = address;
this.serverport = serverport;
// Create client DatagramSocket
this.udpClientSocket = new DatagramSocket();
this.udpClientSocket.connect(serverIPAddress, serverport);
}
public void halt() {
this.stopped = true;
}
public DatagramSocket getSocket() {
return this.udpClientSocket;
}
public void run() {
try {
//send blank message
byte[] data = new byte[1024];
data = "".getBytes();
DatagramPacket blankPacket = new DatagramPacket(data,data.length , serverIPAddress, serverport);
udpClientSocket.send(blankPacket);
// Create input stream
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
while (true)
{
if (stopped)
return;
// Message to send
String clientMessage = inFromUser.readLine();
if (clientMessage.equals("."))
break;
// Create byte buffer to hold the message to send
byte[] sendData = new byte[1024];
// Put this message into our empty buffer/array of bytes
sendData = clientMessage.getBytes();
// Create a DatagramPacket with the data, IP address and port number
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverport);
// Send the UDP packet to server
System.out.println("I just sent: "+clientMessage);
udpClientSocket.send(sendPacket);
Thread.yield();
}
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
class ReceiverThread extends Thread {
private DatagramSocket udpClientSocket;
private boolean stopped = false;
public ReceiverThread(DatagramSocket ds) throws SocketException {
this.udpClientSocket = ds;
}
public void halt() {
this.stopped = true;
}
public void run() {
// Create a byte buffer/array for the receive Datagram packet
byte[] receiveData = new byte[1024];
while (true) {
if (stopped)
return;
// Set up a DatagramPacket to receive the data into
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
System.out.println("I am in the reader!");
try {
// Receive a packet from the server (blocks until the packets are received)
udpClientSocket.receive(receivePacket);
System.out.println("Am i receiving?");
// Extract the reply from the DatagramPacket
String serverReply = new String(receivePacket.getData(), 0, receivePacket.getLength());
// print to the screen
System.out.println("UDPClient: Response from Server: \"" + serverReply + "\"\n");
Thread.yield();
}
catch (IOException ex) {
System.err.println(ex);
}
}
}
}
这是我的 Server.java
import java.net.*; // Imported because the Socket class is needed
import java.util.HashSet;
public class Server {
private static HashSet<Integer> portSet = new HashSet<Integer>();
public static void main(String args[]) throws Exception {
// The default port
int serverport = 4000;
if (args.length < 1) {
System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport);
}
// Get the port number & host to use from the command line
else {
serverport = Integer.valueOf(args[0]).intValue();
System.out.println("Usage: UDPServer " + "Now using Port# = " + serverport);
}
// Open a new datagram socket on the specified port
DatagramSocket udpServerSocket = new DatagramSocket(serverport);
System.out.println("Server started...\n");
while(true)
{
// Create byte buffers to hold the messages to send and receive
byte[] receiveData = new byte[1024];
// Create an empty DatagramPacket packet
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
// Block until there is a packet to receive, then receive it (into our empty packet)
udpServerSocket.receive(receivePacket);
// Extract the message from the packet and make it into a string, then trim off any end characters
String clientMessage = (new String(receivePacket.getData())).trim();
// Print some status messages
System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress());
System.out.println("Client message: \"" + clientMessage + "\"");
// Get the IP address and the the port number which the received connection came from
InetAddress clientIP = receivePacket.getAddress();
// Print out status message
System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n");
// Get the port number which the recieved connection came from
int clientport = receivePacket.getPort();
System.out.println("Adding "+clientport);
portSet.add(clientport);
// Response message
String returnMessage = clientMessage.toUpperCase();
System.out.println(returnMessage);
// Create an empty buffer/array of bytes to send back
byte[] sendData = new byte[1024];
// Assign the message to the send buffer
sendData = returnMessage.getBytes();
for(Integer port : portSet)
{
System.out.println(port != clientport);
if(port != clientport)
{
// Create a DatagramPacket to send, using the buffer, the clients IP address, and the clients port
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientIP, port);
System.out.println("Sending");
// Send the echoed message
udpServerSocket.send(sendPacket);
}
}
}
}
}
答案 0 :(得分:1)
在客户端代码中,您正在连接到localhost,这意味着127.0.0.1仅绑定到您的系统。
如果从另一个系统尝试,则应使用运行服务器的计算机的IP(如果在Windows上,请使用命令ipconfig
),也可以在网关IP上广播。
搜索Google以Java广播UDP。
答案 1 :(得分:0)
它无效,因为您将UDP套接字连接到本地主机&#39;。