2012-01-24 2 views
0

최근에 Android 앱을 제작하고 있으며 네트워킹 관련 문제가 있습니다. 처음에는 this 오류가 발생했으며 프로그램을 업그레이드했지만 지금은 또 다른 문제가 있습니다. 나는 그것을 보내는 자신의 스레드와받는 다른 클래스를 시작하는 별도의 클래스가 있습니다. 여기에 보내기위한 하나입니다Android의 MulticastSocket을 통해 데이터를 수신 할 때 문제가 발생합니다.

import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.InetAddress; 
import java.net.MulticastSocket; 

import android.widget.EditText; 

public class Sender implements Runnable { 

    private MulticastSocket so; 
    private InetAddress serverAddress; 
    private int port; 
    private EditText messageBoard; 
    private EditText eText1; 
    private EditText eText2; 
    private EditText eText3; 
    private Thread myActivity = new Thread(this); 

    public Sender(EditText etHost, EditText etPort, EditText messageBoard, EditText etSend) { 
     eText1 = etHost; 
     eText2 = etPort; 
     eText3 = etSend; 
     this.messageBoard = messageBoard; 
     myActivity.start(); 
    } 

    @Override 
    public void run() { 

     // convert the host name to InetAddress 
     try { 
      //serverAddress = InetAddress.getByName(eText1.getText().toString()); 
      serverAddress = InetAddress.getByName("atlas.dsv.su.se"); 
     } catch (Exception e) {} 

     //convert the port to an int 
     //port = Integer.parseInt(eText2.getText().toString()); 
     port = 4456; 

     // create socket and start communicating 
     try { 
      so = new MulticastSocket(port); 
      so.joinGroup(serverAddress); 
     } catch (IOException e) {} 

     // start listening for incoming messages 
     new Receiver(so, messageBoard); 
    } 

    /** 
    * This method copies the text from the input text field to the conversation text field and 
    * cleans the input text field 
    */ 
    public void sendMessage() { 

     // get the text that they contain and add the new messages to the old ones 
     String message = eText3.getText().toString(); 
     String conversation = messageBoard.getText().toString(); 
     String newConverstion = conversation.concat("\n[You] ").concat(message); 

     // make the messages text view editable 
     messageBoard.setFocusable(true); 
     messageBoard.setText(newConverstion); // add the new message to the text view 
     messageBoard.setFocusable(false); // make the messages text view not editable 

     // erase the text on the second text view that has just been sent 
     eText3.setText(""); 

     // Send message to server 

     // convert message to bytes array 
     byte[] data = (message).getBytes(); 

     // create and send a datagram 
     DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, port); 

     try { 
      so.send(packet); 
     } catch (IOException e) {} 


    } // end of sendMessage 

} 

는 여기 수신을위한 하나입니다

import java.io.IOException; 
import java.net.DatagramPacket; 
import java.net.MulticastSocket; 

import android.widget.EditText; 

public class Receiver implements Runnable { 

    private Thread myActivity = new Thread(this); 
    private MulticastSocket so; 
    private EditText messageBoard; 

    public Receiver(MulticastSocket sock, EditText messBo) { 
     so = sock; 
     messageBoard = messBo; 
     myActivity.start(); 
    } 

    @Override 
    public void run() { 
     byte[] data = new byte[1024]; // received data container 

     while (true) { 
      try { 
       // create a datagram for receiving 
       DatagramPacket packet = new DatagramPacket(data, data.length); 

       // wait for the next message 
       so.receive(packet); 

       String message = new String(data, 0, packet.getLength()); 

       // add the new messages to the old ones 
       String conversation = messageBoard.getText().toString(); 
       String newConverstion = conversation.concat("\n[Remote] ").concat(message); 

       // make the messages text view editable 
       messageBoard.setFocusable(true); 
       messageBoard.setText(newConverstion); // add the new message to the text view 
       messageBoard.setFocusable(false); // make the messages text view not editable 


      } catch (IOException ioe) {} 
     } 
    } 

} 

내가 그것을 실행하면 내가 얻을 :

01-25 00:23:27.281: W/dalvikvm(582): threadid=12: thread exiting with uncaught exception (group=0x409c01f8) 
01-25 00:23:27.281: E/AndroidRuntime(582): FATAL EXCEPTION: Thread-80 
01-25 00:23:27.281: E/AndroidRuntime(582): java.lang.NullPointerException 
01-25 00:23:27.281: E/AndroidRuntime(582): at com.regeduser00x.proj1.Receiver.run(Receiver.java:31) 
01-25 00:23:27.281: E/AndroidRuntime(582): at java.lang.Thread.run(Thread.java:856) 

라인 (31)은 무엇이며 so.receive(packet);입니다 그 문제?

+0

. run'이라면'try' /'catch '쌍을 가질 수 있습니다.하지만 예외가 있다면 아무 것도하지 않고 func을 보냅니다. 계속해서 아무 일도 일어나지 않았습니다. 'try' 내부의 코드가 실패하면'null' 참조가 생길 수 있습니다. –

답변

0

가장 좋은 추측은 소켓이 수신기 생성자 null에 들어오는 것입니다. 그러나 당신이 어떻게 이것을 사용하려고하는지 보지 않고 나는 확실히 말할 수 없을 것입니다.

AsyncTask를 사용하여 클래스를 구현하는 것이 더 간단하다고 말할 수 있습니다. 특히 스레드를 쉽게 만들고 상호 작용할 수 있도록 만들어졌습니다.

다음은 귀하가 달성하고자하는 것을 보좌 해줄 몇 가지 사항입니다.

이러한 두 현상 문서의 일부 :

http://developer.android.com/resources/articles/painless-threading.html

http://developer.android.com/reference/android/os/AsyncTask.html

하고 이는 AsyncTask를 사용의 좋은 예를 가지고 발신자 '에서

http://www.screaming-penguin.com/node/7746

+0

재미있어 보이지만 매개 변수로 그 부분을 얻지는 못합니다. 인터페이스 구성 요소를 'AsyncTask '유형으로 전달할 수없는 경우 인터페이스에서 정보를 읽고이를 인터페이스로 다시 보내려면 어떻게해야합니까? – RegedUser00x

+0

실제로 Receiver를 비활성화했으며 전송하려고하면 충돌이 발생합니다. 그래서 내가 뭔가를 보내고받지 못하게하지만 별도의 스레드에이 있습니다. 솔루션은 AsyncTask를 사용하는 것일 수 있습니다. 누군가가 AsyncTask로 어떻게 재 작성 될 수 있는지 간단한 예제를 제공 할 것입니까? – RegedUser00x

관련 문제