在java中创建UDP广播发送代理 [英] Create an UDP broadcast Sending agent in java

查看:90
本文介绍了在java中创建UDP广播发送代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我是java的新手。

我希望从客户端向所有监听服务器播放java中的meesage。我不想要广播到任何特定的机器,因此我192.168.1.255作为代码中的IP地址,但仍然不发送数据包到监听服务器。但是当我使用特定的IP地址它只是工作正常。代码如下:



Hi all,
I am a newbie in java.
I am looking to broadcast a meesage in java from the client to all the listening servers.I dont want to broadcast to any particular machine hence i am 192.168.1.255 as the ip address in the code but still doesnot send the packets to the listening servers.However when i use a specific ip adress it just works fine.Code is as follows:

import java.io.*; 
import java.net.*; 

public class client {

	public static void main(String args[]) throws Exception    
	{      		
		while(true)
		{
		
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
		DatagramSocket clientSocket = new DatagramSocket(); 
		clientSocket.setBroadcast(true);
		
		InetAddress IPAddress = InetAddress.getByName("192.168.1.255"); 
		byte[] sendData = new byte[50];   
		byte[] receiveData = new byte[50];  
		String sentence = inFromUser.readLine();   
		sendData = sentence.getBytes();    
		DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,new InetSocketAddress("192.168.1.255",9876)); 
		clientSocket.send(sendPacket); 
		DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);   
		clientSocket.receive(receivePacket); 
		String modifiedSentence = new String(receivePacket.getData());  
		System.out.println("FROM SERVER:" + modifiedSentence);   
		clientSocket.close();    
		}
	} 

}





任何帮助都会非常感激。



提前谢谢



Any help would really be appreciated.

Thanks in advance

推荐答案

您的广播地址需要考虑您的子网掩码,如< a href =http://en.wikipedia.org/wiki/Broadcast_address> http://en.wikipedia.org/wiki/Broadcast_address [ ^ ]。
Your broadcast address needs to take account of your subnet mask as described in http://en.wikipedia.org/wiki/Broadcast_address[^].


这篇关于在java中创建UDP广播发送代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆