I'm writing a java chat application using Multicast.
The clients can communicate among themselves but they can also send predefined messages to the server who always has the same answer to the respective predefined message.
Both client and server can receive and send messages. They are both subscribing recipients to the same host and port, so their sockets are the same, but when a client is sending a predefined message to the server, the server gets stuck in an infinite loop receiving the same message.
Code Server
final Lock lock = new ReentrantLock();
final Condition Rx = lock.newCondition();
final Condition Tx = lock.newCondition();
private volatile boolean msgRead;
private volatile int TypeMsg;
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
/*
Thread Rx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
lock.lock();
try{
while(msgRead == true)
Rx.await();
byte[] buf = new byte[256];
DatagramPacket packetRx = new DatagramPacket(buf, buf.length);
try{
MSocket.receive(packetRx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
String received = new String(packetRx.getData(), 0, packetRx.getLength());
if("end".equals(received))
break;
if(received.contains("WEATHER_FORECAST") == true)
TypeMsg = 1;
else
if(received.contains("ASK_AGE_CAPTAIN") == true)
TypeMsg = 2;
msgRead = true;
Tx.signal();
}catch(InterruptedException ie){
System.out.println("Thread Rx -> " + ie.getMessage());
}
finally{
lock.unlock();
}
}
}
}.start();
/*
Thread Tx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
lock.lock();
try{
while(msgRead == false)
Tx.await();
byte[] buf = new byte[256];
/* switch(TypeMsg){...} */
buf = text.getBytes();
DatagramPacket packetTx = new DatagramPacket(buf, buf.length, group, port_chat);
try{
MSocket.send(packetTx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
msgRead = false;
Rx.signal();
}catch(InterruptedException ie){
System.out.println("Thread Tx -> " + ie.getMessage());
}finally{
lock.unlock();
}
}
}
}.start();
Code Client
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
/*
Thread Rx
*/
new Thread(){
#Override
public void run(){
while(!isInterrupted()){
byte[] buf = new byte[256];
DatagramPacket packetRx = new DatagramPacket(buf, buf.length);
try{
MSocket.receive(packetRx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
String received = new String(packetRx.getData(), 0, packetRx.getLength());
if("end".equals(received))
break;
jTextArea_Rx.append(received + "\n");
}
}
}.start();
/*
Tx
*/
private void jButton_SendActionPerformed(java.awt.event.ActionEvent evt) {
byte[] buf = new byte[256];
String text = username + " >> " + jTextArea_Tx.getText();
buf = text.getBytes();
DatagramPacket packetTx = new DatagramPacket(buf, buf.length, group, port_chat);
try{
MSocket.send(packetTx);
}catch(IOException ioe){
System.out.println(this.toString() + " IOException -> " + ioe.getMessage());
}
}
This feels like it has something to do with the IP_MULTICAT_LOOP socket option which is surprisingly enabled by default in Java Multicast Sockets. Basically when this flag is enabled, you will receive messages you send on the multicast socket. So if you also send a message when you receive a message and you have this enabled, then you can create a loop.
Try disabling this socket option and see what happens.
I got it, I had to add
System.setProperty("java.net.preferIPv4Stack", "true");
at the beginning of the application and I also changed this part
try{
NetworkInterface nif = NetworkInterface.getByName("en1");
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(new InetSocketAddress(adresse_chat, port_chat), nif);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
to
try{
MSocket = new MulticastSocket(port_chat);
group = InetAddress.getByName(adresse_chat);
MSocket.joinGroup(group);
}catch(IOException se){
System.out.println(this.toString() + " IOException -> " + se.getMessage());
}
so no need to explicitly specifying the interface. I found the answer after some time here: Getting `Can't assign requested address` java.net.SocketException using Ehcache multicast
Related
I am coding client-server multithread calculator using java, socket programming.
There's any syntax error, but msgs cannot be received from server.
I think
receiveString = inFromServer.readLine()
does not works. This code is in Client program, in the while(true) loop.
What is the problem?
Here is my full code.
SERVER
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
static int max = 5; //maximum thread's number
static int i = 0, count = 0; //i for for-loop, count for count number of threads
public static void main(String args[]) throws IOException
{
ServerSocket serverSocket = new ServerSocket(6789); //open new socket
File file = new File("src/serverinfo.dat"); //make data file to save server info.
System.out.println("Maximum 5 users can be supported.\nWaiting...");
for(i=0; i <= max; i++) { new Connection(serverSocket); } //make sockets - loop for max(=5) times
try //server information file writing
{
String dataString = "Max thread = 5\nServer IP = 127.0.0.1\nServer socket = 6789\n";
#SuppressWarnings("resource")
FileWriter dataFile = new FileWriter(file);
dataFile.write(dataString);
}
catch(FileNotFoundException e) { e.printStackTrace(); }
catch(IOException e) { e.printStackTrace(); }
}
static class Connection extends Thread
{
private ServerSocket serverSocket;
public Connection(ServerSocket serverSock)
{
this.serverSocket = serverSock;
start();
}
public void run()
{
Socket acceptSocket = null;
BufferedReader inFromClient = null;
DataOutputStream msgToClient = null;
String receiveString = null;
String result = "", sys_msg = "";
try
{
while(true)
{
acceptSocket = serverSocket.accept(); // 접속수락 소켓
count++;
inFromClient = new BufferedReader(new InputStreamReader(acceptSocket.getInputStream()));
msgToClient = new DataOutputStream(acceptSocket.getOutputStream());
System.out.println(count + "th client connected: " + acceptSocket.getInetAddress().getHostName() + " " + count + "/" + max);
System.out.println("Waiting response...");
while(true)
{
if (count >= max+1) // if 6th client tries to access
{
System.out.println("Server is too busy. " + max + " clients are already connected. Client access denied.");
sys_msg = "DENIED";
msgToClient.writeBytes(sys_msg);
acceptSocket.close();
count--;
break;
}
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
try{ receiveString = inFromClient.readLine(); }
catch(Exception e) // if receiveString = null
{
System.out.println("Connection Close");
count--;
break;
}
System.out.println("Input from client : " + receiveString);
try
{
if(receiveString.indexOf("+") != -1) { result = cal("+", receiveString); }
else if(receiveString.indexOf("-") != -1) { result = cal("-", receiveString); }
else if(receiveString.indexOf("/") != -1) { result = cal("/", receiveString); }
else if(receiveString.indexOf("*") != -1) { result = cal("*", receiveString); }
else if(receiveString.indexOf("+") == -1 || receiveString.indexOf("-") == -1 || receiveString.indexOf("*") == -1 || receiveString.indexOf("/") == -1) { result = "No INPUT or Invalid operation"; }
}
catch(Exception e){ result = "Wrong INPUT"; }
try{ msgToClient.writeBytes(result); }
catch(Exception e) {}
}
}
}
catch(IOException e) { e.printStackTrace(); }
}
}
private static String cal(String op, String recv) //function for calculating
{
double digit1, digit2; //first number, second number
String result = null;
digit1 = Integer.parseInt(recv.substring(0, recv.indexOf(op)).trim());
digit2 = Integer.parseInt(recv.substring(recv.indexOf(op)+1, recv.length()).trim());
if(op.equals("+")) { result = digit1 + " + " + digit2 + " = " + (digit1 + digit2); }
else if(op.equals("-")) { result = digit1 + " - " + digit2 + " = " + (digit1 - digit2); }
else if(op.equals("*")) { result = digit1 + " * " + digit2 + " = " + (digit1 * digit2); }
else if(op.equals("/"))
{
if(digit2 == 0){ result = "ERROR OCCURRED: Cannot be divided by ZERO"; }
else{ result = digit1 + " / " + digit2 + " = " + (digit1 / digit2); }
}
return result;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
-----------------------------------------------------------------
CLIENT
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket clientSocket = null;
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromServer = null;
DataOutputStream msgToServer = null;
String sendString = "", receiveString = "";
try
{
clientSocket = new Socket("127.0.0.1", 6789); //make new clientSocket
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
msgToServer = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Input exit to terminate");
System.out.println("Connection Success... Waiting for permission");
while(true)
{
receiveString = inFromServer.readLine();
if(receiveString.equals("DENIED"))
{
System.out.println("Server is full. Try again later.");
break;
}
else { System.out.println("Connection permitted."); }
System.out.print("Input an expression to calculate(ex. 3+1): ");
sendString = userInput.readLine();
if(sendString.equalsIgnoreCase("exit")) //when user input is "exit" -> terminate
{
clientSocket.close();
System.out.println("Program terminated.");
break;
}
try { msgToServer.writeBytes(sendString); }
catch(Exception e) {}
try { receiveString = userInput.readLine(); }
catch(Exception e) {}
System.out.println("Result: " + receiveString); //print result
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
You've set up your server socket stack wrong.
Your code will make 5 threads, each calling accept on a serversocket.
The idea is to have a single ServerSocket (and not 5, as in your example). Then, this single serversocket (running in a single thread that handles incoming sockets flowing out of this serversocket) will call .accept which will block (freeze the thread) until a connection is made, and will then return a Socket object. You'd then spin off a thread to handle the socket object, and go right back to the accept call. If you want to 'pool' (which is not a bad idea), then disassociate the notion of 'handles connections' from 'extends Thread'. For example, implement Runnable instead. Then pre-create the entire pool (for example, 10 threads), have some code that lets you 'grab a thread' from the pool and 'return a thread' to the pool, and now the serversocket thread will, upon accept returning a socket object, grab a thread from the pool (which will block, thus also blocking any incoming clients, if every thread in the pool is already taken out and busy handling a connection), until a thread returns to the pool. Alternatively, the serversocket code checks if the pool is completely drained and if so, will put on a final thread the job of responding to that client 'no can do, we are full right now'.
I'm not sure if you actually want that; just.. make 1 thread per incoming socket is a lot simpler. I wouldn't dive into pool concepts until you really need them, and if you do, I'd look for libraries that help manage them. I think further advice on that goes beyond the scope of this question, so I'll leave the first paragraph as an outlay of how ServerSocket code ought to work, for context.
I have the same code written for both server and client when attempting to upload a file to the server or download it from the server.
Downloading from the server works just fine and no data is missing in my file, but for some reason when uploading the file, not all is transmitted.
For instance, the file size on my client is smaller then when it is on the server. Then when it is opened up on the server, not all of it is there (since not all of it was received)
Server:
Algorithm:
Get message from client
Client tells server it wants to send a file (push)
Server reads where to put the file, and then receives the file from the client
public static void GetClientMessage() {
while (true) {
try {
try {
try {
serverSocket = new ServerSocket(PORT_NUMBER);
} catch (IOException ex) {
System.out.println("GetClientMessage():serverSocket:IOException:ex " + ex);
SendBackException(ex.toString()); // Inform client
}
try {
System.out.println("Waiting for client");
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("GetClientMessage():socket = serverSocket.accept():IOException:ex " + ex);
SendBackException(ex.toString()); // Inform client
}
bufOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
brffReadIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
// 1 - Read Line (it is the flag)
flag = brffReadIn.readLine();
// 2 - Handle Flag
HandleClientMessage(flag);
// Make decisions based upon that message
} catch (IOException ex) {
System.out.println("GetClientMessage():IOException:ex: " + ex);
SendBackException(ex.toString()); // Inform client
}
socket.close();
serverSocket.close();
} // Close while loop
catch (IOException ex) {
System.out.println("GetClientMessage:serverSocket.close():IOException:ex " + ex);
}
}
}
public static void HandleClientMessage(String message) {
System.out.println("HandleClientMessage:message: '" + message + "'");
switch (message) {
case "push":
GetClientFile();
break;
case "open_cla":
OpenCla();
break;
case "kill_cla":
KillCla();
break;
case "get":
SendFile();
break;
default:
break;
}
}
// Gets path to where to place file on local
public static String GetPath() {
String filePath = " ";
try {
bufOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
brffReadIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
filePath = brffReadIn.readLine();
System.out.println("Path to place file on local: " + filePath);
} catch (IOException ex) {
System.out.println(("GetPath():IOException:ex: " + ex));
}
return filePath;
}
public static void GetClientFile() {
// Get the location where to place the file on local
fileOnLocal = GetPath();
int count;
try {
File file = new File(fileOnLocal);
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16* 1024];
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream(fileOnLocal);
while ((count = in.read(bytes)) > 0) {
System.out.println("strByteArray: " + strByteArray);
out.write(bytes, 0, count);
}
out.flush();
System.out.println("File Size in bytes: " + file.length());
if (file.length() < 5) {
System.out.println("FileClient:Error:File:" + fileOnLocal + " not found on server");
out.close();
in.close();
socket.close();
file.delete();
System.out.println("File:" + file.getAbsolutePath() + " deleted");
} else {
out.close();
in.close();
socket.close();
}
} catch (IOException ex) {
System.out.println(":FileClient:GetServerFile():IOException:ex:" + ex);
}
}
Client Code:
Client tells the server it wants to "push" a file, then it passes the location where to put it on the server, then transmits the file
public void SendFlagToServer(String flag){
try {
bufOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
brffReadIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
bufOut.write(flag);
bufOut.newLine();
bufOut.flush();
System.out.println(host + ":SendFlagToServer: " + flag);
} catch (IOException ex) {
Logger.Log((host + ":FileClient:SendFileToGetToServer():IOException:ex: " + ex));
}
}
After performing this the bytes are received on the client, but not all of them. Is there something I have coded wrong? Should my byte[] array be a different size? This will be used on Win7 & Win8, and possibly Mac in the future.
Edit: I figured it out. I was trying to send a message followed by a string of bytes too quickly.
This fixed my problem:
SendFlagToServer(fileLocaitonOnServer);
Thread.sleep(1000);
....
You are closing sockets after first client conneciton
socket.close();
serverSocket.close();
Solution:
Once you accept a client socket, create a new Thread with the socket connection and handle all IO operations in that thread
Do not close serverSocket. Once you close serverSocket, no more client socket connections will be accepted.
Can you provide the exception you are getting?
I have posted my java proxy code below.
It works but it only gives me 1 server response instead of everything.
After the 1 response I just get client sent packets but with a size of 0.
Screenshots also attached.
Any ideas?
I've done some debugging. If I remove everything in between
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
Which is from the reading server response code it works and I get the client packets. How come it doesn't work with server packets?
Code:
import java.io.*;
import javax.xml.bind.DatatypeConverter;
import java.net.*;
public class proxy{
public static void main(String[] args) throws IOException {
//PrintStream out = new PrintStream(new FileOutputStream("log.txt"));
//System.setOut(out);
try{
String host = "gamea.clashofclans.com";
int remoteport = 9339;
ServerSocket ss = new ServerSocket(9339);
int localport = ss.getLocalPort();
ss.setReuseAddress(true);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport
+ " on port " + localport);
// And start running the server
runServer(host, remoteport, localport,ss); // never returns
System.out.println("Started proxy!");
} catch (Exception e) {
System.out.println("Failed to start proxy" +e+ "");
}
}
public static void runServer(String host, int remoteport, int localport, ServerSocket ss)
throws IOException {
final byte[] request = new byte[2048];
byte[] reply = new byte[4096];
while (true) {
Socket client = null, server = null;
try {
System.out.println("Waiting for Client");
client = ss.accept();
System.out.println("Client Accepted!");
DataInputStream streamFromClient = new DataInputStream(client.getInputStream());
DataOutputStream streamToClient = new DataOutputStream(client.getOutputStream());
System.out.println("Connecting to server...");
// Make a connection to the real server.
server = new Socket("gamea.clashofclans.com", 9339);
System.out.println("Just connected client to " + server.getRemoteSocketAddress());
DataInputStream streamFromServer = new DataInputStream(server.getInputStream());
DataOutputStream streamToServer = new DataOutputStream(server.getOutputStream());
Thread t = new Thread() {
public void run() {
int bytesRead;
int type;
int size;
int version;
try {
while ((bytesRead = streamFromClient.read(request)) != -1) {
type = streamFromClient.readUnsignedShort();
size = streamFromClient.readUnsignedShort();
size <<= 8;
size |= streamFromClient.readUnsignedByte();
version = streamFromClient.readUnsignedByte();
byte[] data = new byte[size];
streamFromClient.readFully(data, 0, size);
String FullHex = DatatypeConverter.printHexBinary(data);
System.out.println("Client sending data to server:");
System.out.println("Type: " + type + "");
System.out.println("Data Size: " + size + "");
System.out.println("Version: " + version + "");
System.out.println("Full Data: " + FullHex + "");
System.out.println("\n\n");
streamToServer.write(request, 0, bytesRead);
streamToServer.flush();
}
} catch (IOException e) {
}
// the client closed the connection to us, so close our
// connection to the server.
try {
streamToServer.close();
} catch (IOException e) {
}
}
};
t.start();
int bytesRea;
int typ;
int siz;
try {
while ((bytesRea = streamFromServer.read(reply)) != -1) {
typ = streamFromServer.readUnsignedShort();
siz = streamFromServer.readUnsignedShort();
siz <<= 8;
siz |= streamFromServer.readUnsignedByte();
byte[] dat = new byte[siz];
streamFromServer.readFully(dat, 0, siz);
String FullHe = DatatypeConverter.printHexBinary(dat);
System.out.println("Server sending data to Client:");
System.out.println("Type: " + typ + "");
System.out.println("Data Size: " + siz + "");
System.out.println("Full Data: " + FullHe + "");
System.out.println("\n\n");
streamToClient.write(reply, 0, bytesRea);
streamToClient.flush();
}
} catch (IOException e) {
}
} catch (IOException e) {
System.err.println(e);
} finally {
try {
if (server != null)
server.close();
if (client != null)
client.close();
} catch (IOException e) {
}
}
}
}
}
This doesn't make sense. You're reading up to 4096 bytes from the server and then reading two type bytes and three length bytes and what you think is the request data, and writing what you read originally. So you're consuming the data about twice.
This can't work. You need to either just read the type, length, and value, and write them out again, or else, much more simply, just copy bytes from the input to the output, in both directions. (That way of course you can't do logging.)
NB Don't ignore IOExceptions, and especially not EOFExceptions when reading from DataInputStreams (or ObjectInputStreams).
I am trying to send a text file from the sender to the receiver however on the sender side I get connection refused: connect. I use a localhost address on the receiver side and I manually enter it in when prompt on the sender side. The error occurs at sendChannel.connect(address) in the sender class.
Sender class:
public static void startProcess(){
SocketChannel sendChannel = null;
RandomAccessFile f = null;
Scanner scan = new Scanner(System.in);
SocketAddress address = null;
try{
sendChannel = SocketChannel.open(); // open the channel
//DatagramSocket socket = dChannel.socket();
boolean validAddr = false;
while(validAddr != true){
try{
System.out.println("Enter in valid server IP Address");
address = new InetSocketAddress(scan.nextLine(),7777);
validAddr = true;
}
catch(Exception e){
System.out.println("Invalid!");
System.out.println(e.getMessage());
}
}
//System.out.println("Address: " + InetAddress.getLocalHost().getHostAddress());
sendChannel.connect(address);
File i = new File("./data.txt");
f = new RandomAccessFile(i,"r");
FileChannel fChannel = f.getChannel();
ByteBuffer bBuffer = ByteBuffer.allocate(1024); //set buffer capacity to 1024 bytes
while (fChannel.read(bBuffer) > 0) {
//SocketAddress client = dChannel.receive(bBuffer); //receive the datagram
bBuffer.flip(); //Set limit to current position
sendChannel.write(bBuffer);
//dChannel.send(bBuffer, client); //send the datagram using channel
bBuffer.clear(); //Get ready for new sequence of operations
}
Thread.sleep(1000);
System.out.println("End of file reached");
sendChannel.close();
f.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
Receiver side:
public static void startProcess(){
Scanner scan = new Scanner(System.in);
ServerSocketChannel serverChannel = null;
SocketChannel chan = null;
RandomAccessFile file = null;
try{
serverChannel = ServerSocketChannel.open();
//Read in a valid IP Address
boolean val2 = false;
int tempNum = 0;
for (int portNUM = 7777 ;!val2; portNUM++){
try {
serverChannel.socket().bind(new InetSocketAddress("localhost", portNUM));
tempNum = portNUM;
val2 =true;
} catch (IOException e) {
System.out.println("Error!");
}
}
System.out.println(InetAddress.getLocalHost().getHostAddress());
System.out.println("Port Number: " + tempNum);
chan = serverChannel.accept();
System.out.println("Connected!");
chan.getRemoteAddress();
file = new RandomAccessFile("./output.txt","rw");
ByteBuffer buff = ByteBuffer.allocate(1024);
FileChannel receiveChannel = file.getChannel();
while(chan.read(buff) > 0){
buff.flip();
receiveChannel.write(buff);
buff.clear();
}
// buff.put((byte)65 );
//buff.flip();
Thread.sleep(1000);
receiveChannel.close();
System.out.println("End of file");
chan.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
I figured it out I was using the localhost incorrectly on the Receiver side. I changed it to serverChannel.socket().bind(new InetSocketAddress(portNUM));
I'm trying to code a UDP client to receive packets from a server that is broadcasting on the local network. The problem is the receive method isn't blocking and waiting for a packet to arrive.
Instead, it's receiving null or empty packets.
I've tried to use .setSoTimeout(0), which supposedly will tell the receive to block until it receives a packet, but it doesn't.
Does anyone know how to fix this?
Here's the code:
while (search == true) {
InetAddress addr = InetAddress.getByName("0.0.0.0");
DatagramSocket sock = new DatagramSocket(1355);
sock.setSoTimeout(0);
byte[] recebe = new byte[1024];
sock.setBroadcast(true);
System.out.println("entrou1");
DatagramPacket packet = new DatagramPacket(recebe, recebe.length);
System.out.println("entrou2");
sock.receive(packet);
String info = new String(packet.getData());
System.out.println("tamanho: " + info.length());
if (info.trim().equals("") == false && info != null) {
System.out.println("entrou aqui");
System.out.println("info recebida:" + info + ":fsadfsfs");
String servs[] = info.split("\n");
list1.clear();
servidores.clear();
for (int i = 0; i < servs.length; i++) {
System.out.println("vec: " + servs[i]);
if (servs[i].trim().equals("")) {
System.out.println("break;");
break;
} else {
String aux = servs[i].substring(0, servs[i].lastIndexOf("->"));
System.out.println("aux: " + aux);
list1.add(aux);
servidores.add(servs[i]);
}
}
}
System.out.println("info:\n" + info);
sock.close();
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException ex) {
Logger.getLogger(AcederPartilhaGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}