服务器无法向客户端发送消息

时间:2014-06-16 07:06:39

标签: android serversocket

我想创建一个服务器和客户端相互通信的应用程序。代码......

服务器端:

 public class MainActivity extends ActionBarActivity {

private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
Socket clientSocket;
  private TextView text;
  EditText edit;
  Button b;
  public static final int SERVERPORT = 6000;
  String TimeStamp;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println("inside onCreate");

        text = (TextView) findViewById(R.id.textView1);

        updateConversationHandler = new Handler();
        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();

        TimeStamp = new java.util.Date().toString();

        b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                try 
                {
                    EditText et = (EditText) findViewById(R.id.editText1);
                    String str = et.getText().toString();
                    text.setText(text.getText().toString()+"Me: "+ str +" On "+TimeStamp+ "\n");

                /*
                    BufferedOutputStream bos=new BufferedOutputStream(socket.getOutputStream());
                    OutputStreamWriter osw= new OutputStreamWriter(bos,"US-ASCII");
                    osw.write(str+" "+TimeStamp);
                    osw.flush();
                    */
                    if(clientSocket==null)
                        Toast.makeText(MainActivity.this, "null socket", Toast.LENGTH_SHORT).show();
                    else
                    {
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(clientSocket.getOutputStream())),
                            true);
                    out.println(str);
                    out.flush();
                    et.setText("");
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    protected void onStop() 
    {
        super.onStop();
        try 
        {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
     }

 class ServerThread implements Runnable 
 {
     public void run() 
     {
         Socket socket = null;
         try 
         {
             serverSocket = new ServerSocket(SERVERPORT);
             serverSocket.setReuseAddress(true);
         } catch (IOException e) {
          e.printStackTrace();
     }

     while (!Thread.currentThread().isInterrupted()) 
     {
        try 
        {
            socket = serverSocket.accept();
            CommunicationThread commThread = new CommunicationThread(socket);
              new Thread(commThread).start();
        } catch (IOException e) {
            e.printStackTrace();
        }

     }
     }
   }
    class CommunicationThread implements Runnable 
    {
        //private Socket clientSocket;
        private BufferedReader input;
        public CommunicationThread(Socket aclientSocket) 
        {
            //this.aclientSocket = clientSocket;
            clientSocket=aclientSocket;
            try {
                //this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
                this.input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                } catch (IOException e) {
                e.printStackTrace();
            }

        }
        public void run() 
        {
            while (!Thread.currentThread().isInterrupted()) 
            {
                try 
                {
                    String read = input.readLine();
                    updateConversationHandler.post(new updateUIThread(read));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class updateUIThread implements Runnable 
    {
        private String msg;
        public updateUIThread(String str) 
        {
            this.msg = str;
        }

        @Override
        public void run() 
        {
            text.setText(text.getText().toString()+"Client: "+ msg +" On "+TimeStamp+ "\n");
        }
    }

}

从客户端发送的消息正确接收到服务器,现在来自服务器的消息写入套接字但无法在客户端读取。

客户端:

public class MainActivity extends ActionBarActivity {

private Socket socket;
Handler updateConversationHandler;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
TextView text;
Button c;
String TimeStamp;

@Override
 public void onCreate(Bundle savedInstanceState) 
{
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main); 

      new Thread(new ClientThread()).start();
      TimeStamp = new java.util.Date().toString();


      c=(Button)findViewById(R.id.button1);
      text = (TextView) findViewById(R.id.textView1);
     c.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            try 
            {
                EditText et = (EditText) findViewById(R.id.editText1);
                String str = et.getText().toString();
                text.setText(text.getText().toString()+"Me: "+ str +"On "+TimeStamp+ "\n");
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),
                        true);
                out.println(str);
                out.flush();
                et.setText("");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}

class ClientThread implements Runnable 
    {

        @Override
        public void run()
        {
            try 
            {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
                CommunicationThread commThread = new CommunicationThread(socket);
                  new Thread(commThread).start();
            } catch (UnknownHostException e1) {
               e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

class CommunicationThread implements Runnable 
{
    private Socket clientSocket;
    private BufferedReader input;
    public CommunicationThread(Socket clientSocket) 
    {
        this.clientSocket = clientSocket;
        try {
            this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
            } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void run() 
    {
        while (!Thread.currentThread().isInterrupted()) 
        {
            try 
            {
                String read = input.readLine();
                Log.d("msg","readString"+read);
                updateConversationHandler.post(new updateUIThread(read));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class updateUIThread implements Runnable 
{
    private String msg;
    public updateUIThread(String str) 
    {
        this.msg = str;
        System.out.println("message in updateThread "+msg);
    }

    @Override
    public void run() 
    {
        System.out.println("message "+msg);
        text.setText(text.getText().toString()+"Server: "+ msg +"On "+TimeStamp+ "\n");
    }
}

}

logcat显示:

D/gralloc_goldfish(1777): Emulator without GPU emulation detected.
W/System.err(1777): java.lang.NullPointerException 
W/System.err(1777):     at    com.example.socketservereg.MainActivity$1.onClick(MainActivity.java:67)
W/System.err(1777):     at android.view.View.performClick(View.java:4240)

W/System.err(1777):     at android.view.View$PerformClick.run(View.java:17721)

W/System.err(1777):     at android.os.Handler.handleCallback(Handler.java:730)

W/System.err(1777):     at android.os.Handler.dispatchMessage(Handler.java:92)

W/System.err(1777):     at android.os.Looper.loop(Looper.java:137)

W/System.err(1777):     at android.app.ActivityThread.main(ActivityThread.java:5103)

W/System.err(1777):     at java.lang.reflect.Method.invokeNative(Native Method)

06-17  W / System.err(1777):at java.lang.reflect.Method.invoke(Method.java:525)

W/System.err(1777):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

W/System.err(1777):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

我是初学者,任何帮助都将受到赞赏......

1 个答案:

答案 0 :(得分:0)

在您使用的服务器中

socket.getOutputStream()

但它应该是

clientSocket.getOutputStream()