本文整理汇总了Java中java.net.MulticastSocket.receive方法的典型用法代码示例。如果您正苦于以下问题:Java MulticastSocket.receive方法的具体用法?Java MulticastSocket.receive怎么用?Java MulticastSocket.receive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.MulticastSocket
的用法示例。
在下文中一共展示了MulticastSocket.receive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: scanResposesForKeywords
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* Scans all messages that arrive on the socket and scans them for the
* search keywords. The search is not case sensitive.
*
* @param socket
* The socket where the answers arrive.
* @param keywords
* The keywords to be searched for.
* @return
* @throws IOException
*/
private String scanResposesForKeywords(MulticastSocket socket,
String... keywords) throws IOException {
// In the worst case a SocketTimeoutException raises
socket.setSoTimeout(2000);
do {
logger.debug("Got an answer message.");
byte[] rxbuf = new byte[8192];
DatagramPacket packet = new DatagramPacket(rxbuf, rxbuf.length);
socket.receive(packet);
String foundIp = analyzePacket(packet, keywords);
if (foundIp != null) {
return foundIp;
}
} while (true);
}
示例2: retrieveResponse
import java.net.MulticastSocket; //导入方法依赖的package包/类
static String retrieveResponse() throws Exception {
String response = null;
MulticastSocket recSocket = setUpSocket();
int i = 0;
while (response == null) {
byte[] buf = new byte[2048];
DatagramPacket input = new DatagramPacket(buf, buf.length);
try {
recSocket.receive(input);
response = new String(input.getData());
} catch (SocketTimeoutException e) {
if (i >= 10) break;
i++;
}
}
return response;
}
示例3: run
import java.net.MulticastSocket; //导入方法依赖的package包/类
public void run() throws Exception {
log.fine("Test started.");
log.fine("Listening for multicast packets at " + connection.address.getHostAddress()
+ ":" + String.valueOf(connection.port));
log.fine(initialLogMessage());
log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds.");
startTime = System.currentTimeMillis();
timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR;
log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds.");
MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000);
byte[] buffer = new byte[BUFFER_LENGTH];
DatagramPacket datagram = new DatagramPacket(buffer, buffer.length);
do {
try {
socket.receive(datagram);
onReceived(extractUDPpayload(datagram));
} catch (SocketTimeoutException e) {
onSocketTimeOut(e);
}
if (hasTestLivedLongEnough()) {
shutdown();
}
} while (shouldContinue());
log.fine("Test ended successfully.");
}
示例4: test
import java.net.MulticastSocket; //导入方法依赖的package包/类
private static void test() throws Exception {
final String hostname = "google.com";
final String localhost = "localhost";
final MulticastSocket datagramSocket = new MulticastSocket();
datagramSocket.setSoTimeout(10000);
short ttl = 1;
final InetAddress receiverAddress = InetAddress.getByName(hostname);
while (ttl < 100) {
try {
byte[] buffer = "0123456789".getBytes();
datagramSocket.setTimeToLive(ttl++);
final DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length, receiverAddress, 80);
datagramSocket.send(sendPacket);
buffer = new byte[10];
final DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
datagramSocket.receive(receivePacket);
System.out.println("ttl=" + ttl + " address=" + receivePacket.getAddress().getHostAddress() + " data="
+ new String(receivePacket.getData()));
Thread.sleep(1000);
} catch (final SocketTimeoutException e) {
System.out.println("timeout ttl=" + ttl);
}
}
}
示例5: main
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws Exception {
InetAddress group = InetAddress.getByName("228.5.6.7");
MulticastSocket s = new MulticastSocket(6789);
byte[] arb = new byte[1024];
s.joinGroup(group);// 加入该组
while (true) {
DatagramPacket datagramPacket = new DatagramPacket(arb, arb.length);
s.receive(datagramPacket);
System.out.println(arb.length);
System.out.println(new String(arb));
}
}
示例6: main
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* @param args
*/
public static void main(String[] args) throws Exception{
int port=9527;
int aport=9528;
InetAddress groupAddress=InetAddress.getByName("224.1.1.1");
MulticastSocket server=new MulticastSocket(port);
server.joinGroup(groupAddress);
MulticastSocket client=new MulticastSocket();
client.joinGroup(groupAddress);
byte[] buffer=new byte[65507];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
while(true){
server.receive(packet);
String line=new String(packet.getData(),0,packet.getLength(),"UTF-8");
if("quit".equalsIgnoreCase(line.trim())){
server.close();
System.exit(0);
}
else{
System.out.println("Message from client: "+ line);
packet.setLength(buffer.length);
String response="Server response��"+line;
byte[] datas=response.getBytes("UTF-8");
DatagramPacket responsePacket=new DatagramPacket(datas,datas.length,groupAddress,aport);
client.send(responsePacket);
Thread.sleep(100);
}
}
}
示例7: main
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* @param args
*/
public static void main(String[] args) throws Exception{
int port=9527;
int aport=9528;
InetAddress groupAddress=InetAddress.getByName("224.1.1.1");
MulticastSocket serverSocket=new MulticastSocket(aport);
serverSocket.joinGroup(groupAddress);
byte[] buffer=new byte[65507];
DatagramPacket receivePacket=new DatagramPacket(buffer,buffer.length);
MulticastSocket socket=new MulticastSocket();
socket.joinGroup(groupAddress);
BufferedReader systemIn=new BufferedReader(new InputStreamReader(System.in));
boolean flag=true;
while(flag){
String command=systemIn.readLine();
byte[] datas=command.getBytes("UTF-8");
DatagramPacket packet=new DatagramPacket(datas,datas.length,groupAddress,port);
socket.send(packet);
if(command==null || "quit".equalsIgnoreCase(command.trim())){
flag=false;
System.out.println("Client quit!");
socket.leaveGroup(groupAddress);
socket.close();
serverSocket.leaveGroup(groupAddress);
serverSocket.close();
continue;
}
serverSocket.receive(receivePacket);
String receiveResponse=new String(receivePacket.getData(),0,receivePacket.getLength(),"UTF-8");
System.out.println(receiveResponse);
}
}
示例8: call
import java.net.MulticastSocket; //导入方法依赖的package包/类
@Override
public Object call() throws Exception {
InetAddress multicastAddress = InetAddress.getByName(this.SSDP_HOST);
MulticastSocket socket = new MulticastSocket(SSDP_PORT);
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
socket.joinGroup(multicastAddress);
byte[] packetBuffer = SSDP_REQUEST().getBytes("UTF-8");
DatagramPacket mSearchPacket = new DatagramPacket(packetBuffer, packetBuffer.length, multicastAddress, SSDP_PORT);
socket.send(mSearchPacket);
/**
* Should run until either:
* - A compatible device is found
* - The socket times out (10000ms)
*/
while(true){
byte[] responseBuffer = new byte[8192];
DatagramPacket packet = new DatagramPacket(responseBuffer, responseBuffer.length);
socket.receive(packet);
String packetAddress = packet.getAddress().getHostAddress();
String fullResponse = new String(responseBuffer, 0, packet.getLength());
/**
* Make sure the response is not from localhost and the USN contains the HEOS urn.
*/
if(!packetAddress.equals(InetAddress.getLocalHost().getHostAddress())){
if(fullResponse.contains(SSDP_ST)){
return packetAddress;
}
}
}
}
示例9: findHeosIp
import java.net.MulticastSocket; //导入方法依赖的package包/类
public String findHeosIp() throws UnknownHostException, IOException{
InetAddress multicastAddress = InetAddress.getByName(this.SSDP_HOST);
MulticastSocket socket = new MulticastSocket(SSDP_PORT);
socket.setReuseAddress(true);
socket.setSoTimeout(10000);
socket.joinGroup(multicastAddress);
byte[] packetBuffer = SSDP_REQUEST().getBytes("UTF-8");
DatagramPacket mSearchPacket = new DatagramPacket(packetBuffer, packetBuffer.length, multicastAddress, SSDP_PORT);
socket.send(mSearchPacket);
/**
* Should run until either:
* - A compatible device is found
* - The socket times out
*/
while(true){
byte[] responseBuffer = new byte[8192];
DatagramPacket packet = new DatagramPacket(responseBuffer, responseBuffer.length);
socket.receive(packet);
String packetAddress = packet.getAddress().getHostAddress();
String fullResponse = new String(responseBuffer, 0, packet.getLength());
/**
* Make sure the response is not from localhost and the USN contains the HEOS urn.
*/
if(!packetAddress.equals(InetAddress.getLocalHost().getHostAddress())){
if(fullResponse.contains(SSDP_ST)){
return packetAddress;
}
}
}
}
示例10: AbletonLink
import java.net.MulticastSocket; //导入方法依赖的package包/类
public AbletonLink() throws IOException {
socket = new MulticastSocket(20808);
addr = NetworkUtilities.multicastAddress('L','N','K');
final Thread receiveThread = new Thread(new Runnable() {
@Override
public void run() {
for (;;) {
try {
if(joined.get()) {
byte[] buffer = new byte[socket.getReceiveBufferSize()];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
process(new AbletonLinkPacket(System.nanoTime() / 1000, packet));
} else {
Thread.sleep(100);
}
} catch (Throwable t) {
log.warning(t);
}
}
}
}, "Ableton Link");
receiveThread.setDaemon(true);
receiveThread.setPriority(Thread.MAX_PRIORITY);
receiveThread.start();
}
示例11: main
import java.net.MulticastSocket; //导入方法依赖的package包/类
public static void main(String[] args) throws UnknownHostException {
System.out.println("Welcome To The Chat Room");
System.out.println("Programmed by ...");
System.out.println("Maxwell - Client side programming");
System.out.println("Kayode - Command selection algorithm");
System.out.println("Chidi - Error, Thowable, Exception and Msg logging");
System.out.println("Yemi - Message command seperation algorithm");
System.out.println("orign master - Sever side programming");
System.out.println();
System.out.println("\nType ';help' to view the available commands!");
System.out.print("Enter your username: ");
username = new Scanner(System.in).nextLine().trim();
addr = InetAddress.getByName(INET_ADDR);
try {
clientSocket = new MulticastSocket(PORT);
clientSocket.joinGroup(addr);
sendMessage("joined the chat room");
new InputThread().start();
while (true) {
// Receive the information and print it.
buf = new byte[256];
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String ip = msgPacket.getAddress().getHostAddress();
String msg = new String(buf);
msg = msg.trim();
printMsg(msg, ip);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
示例12: main
import java.net.MulticastSocket; //导入方法依赖的package包/类
public static void main(String[] args) throws IOException {
InetAddress address = InetAddress.getByName(INET_ADDR);
byte[] buf = new byte[512]; // more than enough for any UDP style packet
MulticastSocket clientSocket = new MulticastSocket(PORT);
// listen for broadcast messages:
clientSocket.joinGroup(address);
while (true) {
DatagramPacket messagePacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(messagePacket);
String message = new String(buf, 0, buf.length);
System.out.println("received broadcast message: " + message);
}
}
示例13: discover
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* Sends a discovery packet for the specified service and listens for reply packets, notifying
* a callback as services are discovered.
* @param serviceType the type of service to query in mDNS, e.g. {@code "_example._tcp.local"}
* @param callback receives callbacks with {@link Result} objects as answers are decoded from
* incoming reply packets.
* @param timeout duration in milliseconds to wait for answer packets. If {@code 0}, this method
* will listen forever.
* @throws IOException
*/
public static void discover(String serviceType, Callback callback, int timeout) throws IOException {
if (timeout < 0) throw new IllegalArgumentException();
InetAddress group = InetAddress.getByName(MULTICAST_GROUP_ADDRESS);
MulticastSocket sock = new MulticastSocket(); // binds to a random free source port
if (DEBUG) System.out.println("Source port is " + sock.getLocalPort());
byte[] data = discoverPacket(serviceType);
if (DEBUG) System.out.println("Query packet:");
if (DEBUG) hexdump(data, 0, data.length);
DatagramPacket packet = new DatagramPacket(data, data.length, group, PORT);
sock.setTimeToLive(255);
sock.send(packet);
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
long endTime = 0;
if (timeout != 0) {
endTime = System.currentTimeMillis() + timeout;
}
while (true) {
if (timeout != 0) {
int remaining = (int) (endTime - System.currentTimeMillis());
if (remaining <= 0) {
break;
}
sock.setSoTimeout(remaining);
}
try {
sock.receive(packet);
} catch (SocketTimeoutException e) {
break;
}
if (DEBUG) System.out.println("\n\nIncoming packet:");
if (DEBUG) hexdump(packet.getData(), 0, packet.getLength());
Result result = decode(packet.getData(), packet.getLength());
if (callback != null) {
callback.onResult(result);
}
}
}
示例14: resolve
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* Ask for the A, SRV and TXT records of a particular service.
* @param serviceName the name of service to query in mDNS, e.g.
* {@code "device-1234._example._tcp.local"}
* @param timeout duration in milliseconds to wait for an answer packet. If {@code 0}, this
* method will listen forever.
* @return the reply packet's decoded answer data
* @throws IOException
*/
public static Result resolve(String serviceName, int timeout) throws IOException {
if (timeout < 0) throw new IllegalArgumentException();
InetAddress group = InetAddress.getByName(MULTICAST_GROUP_ADDRESS);
MulticastSocket sock = new MulticastSocket(); // binds to a random free source port
if (DEBUG) System.out.println("Source port is " + sock.getLocalPort());
if (DEBUG) System.out.println("Query packet:");
byte[] data = queryPacket(serviceName, QCLASS_INTERNET | CLASS_FLAG_UNICAST, QTYPE_A, QTYPE_SRV, QTYPE_TXT);
if (DEBUG) hexdump(data, 0, data.length);
DatagramPacket packet = new DatagramPacket(data, data.length, group, PORT);
sock.setTimeToLive(255);
sock.send(packet);
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
Result result = new Result();
long endTime = 0;
if (timeout != 0) {
endTime = System.currentTimeMillis() + timeout;
}
// records could be returned in different packets, so we have to loop
// timeout applies to the acquisition of ALL packets
while (result.a == null || result.srv == null || result.txt == null) {
if (timeout != 0) {
int remaining = (int) (endTime - System.currentTimeMillis());
if (remaining <= 0) {
break;
}
sock.setSoTimeout(remaining);
}
sock.receive(packet);
if (DEBUG) System.out.println("\n\nIncoming packet:");
if (DEBUG) hexdump(packet.getData(), 0, packet.getLength());
decode(packet.getData(), packet.getLength(), result);
}
return result;
}
示例15: recvData
import java.net.MulticastSocket; //导入方法依赖的package包/类
/**
* Blocking call
*/
public static boolean recvData(MulticastSocket s, byte[] buffer) throws IOException {
s.setSoTimeout(100);
// Create a DatagramPacket and do a receive
final DatagramPacket pack = new DatagramPacket(buffer, buffer.length);
try {
s.receive(pack);
} catch (SocketTimeoutException e) {
return false;
}
// We have finished receiving data
return true;
}