点击Togglebutton发送两个不同的消息

时间:2015-03-25 05:49:43

标签: java android sockets

我有 ToggleButton 。单击该按钮一次,包含消息{(byte)0x01,(byte)0x02}的Byte []必须发送到服务器,当再次单击相同的按钮时,包含msg {(byte)的字节[] 0xFE,(byte)0x01}必须发送到服务器。 我的客户端代码就是这样。

Public void onClick(View v)
 {
  if(v.getId()==R.id.btncon)
   {
    if(con.isChecked())
     {
      new Thread(new Runnable(){
       public void run()
        {
         try{
          InetAddress in=InetAddress.getByName(host);
          s=new Socket(in,port);
          PrintStream pw=new PrintStream(s.getOutputStream());
          pw.println(message);

          InputStream inp=new InputStream(s.getInputStream());
          BufferedReader br=new BufferedReader(inp);
          String user=br.readline();
          Log.d("home",user);
            }
         catch(IOException e)
          {
             e.printStackTrace();
          }
       }
    }).start();
   }
 else
  { 
   try{
    PrintStream pw1=new PrintStream(s.getOutputStream());
    pw.Println(message1);
    s.close();
      }
  catch(IOException e1)
      {
       e1.printStackTrace();
      }}}}

我的服务器代码

public void run() throws Exception
 {
   String MESSAGE;    
   ServerSocket ss=null;
   PrintStream pw=null;
    try 
     {
      ss=new ServerSocket(8002);
     }
   catch(IOException e1)
     {
      e1.printStackTrace();
     }

   while(true)
    {
     try
      {               

       sock=ss.accept();
       in=new InputStreamReader(sock.getInputStream());     
       BufferedReader br=new BufferedReader(in);

       MESSAGE=br.readLine();          
       System.out.println("client sent:"+MESSAGE);

    if(MESSAGE!=null)
     {
      pw=new PrintStream(sock.getOutputStream());
      pw.println("server received the message"+":"+ MESSAGE);
      pw.flush();
     }}                  
  catch(IOException e)
   {
     e.printStackTrace();
   }
 finally{
   in.close();
   pw.close();
   sock.close();
        }}}       

当从客户端发送消息时,当服务器收到并打印该值时,我得到一个不同的值。我希望输出在发送时显示。 请帮忙。谢谢。

服务器和客户端的代码都很有帮助

0 个答案:

没有答案