`
yzhong_sa
  • 浏览: 88800 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类

android与pc的故事

阅读更多





     别以为这里会有什么精彩的故事。。这是android和android的对话:
今天把之前做的聊天器移植到了android上来了,本来想启动两个两个sdk来搞搞,互相说说话。算了,一个都把我的机搞的有点慢了,然后开一个socekt的pc端的客户端来聊聊天吧。。

服务器的设计和之前的差不多,基本就是一个消息广播器,没有什么特别。

好,然后是android的socket客户端了:
源码:
package com.sun.chatdemo;
/**
* @author Sun.Zhong
* @version 1.0
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Date;
import java.sql.Timestamp;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
*
* @param socket :Socket  object.
* @param br:socket message reader.
* @param messageContentText : all the message .
* @param inputMessage:message from android.
* @param nickNameText :nick name for android.
*
*/
public class ChatForm extends Activity implements Runnable {
/** Called when the activity is first created. */
private Socket socket;
private BufferedReader br;
private EditText messageContentText;
private EditText inputMessage;
private String data;
private PrintWriter out;
private EditText nickNameText;
//default constructor
public ChatForm() {
  
}
/**
  * override methord of Activity.
  * android's app starts with activity.
  */
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  /**
   * initial the default variable.
   */
  setContentView(R.layout.chatform);
  Log.e("test conntetion", "start activity");
  Button connectBtn = (Button) findViewById(R.id.connect);
  messageContentText = (EditText)findViewById(R.id.message_content);
  inputMessage = (EditText) findViewById(R.id.message_input);
  nickNameText = (EditText) findViewById(R.id.nick_name);
  Button sendBtn = (Button) findViewById(R.id.sendBtn);
  Button startServerBtn = (Button) findViewById(R.id.start_server);
  
  /**
   * set the listener of the connectBtn.
   * 1.connect with the server,and set the time before this conversation.
   * 2.get the input and out put stream of the socket.
   */
  connectBtn.setOnClickListener(new OnClickListener() {
  // messageContent = (EditText) findViewById(R.id.message_content)    
  public void onClick(View v) {
  
   Log.e("test connectBtn", "prepare to connect with the server..");
   try {
    socket = new Socket(InetAddress.getByName("192.168.0.166"), 5000);
    if(socket.isConnected()){
     //Log.e("time", new String().valueOf(System.currentTimeMillis()));
     messageContentText.setText(new Timestamp(System.currentTimeMillis()).toString()+"\n" );
    }
    br = new BufferedReader(new InputStreamReader(socket
      .getInputStream()));
    out = new  PrintWriter(socket.getOutputStream());
   } catch (UnknownHostException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   }
  });
  /**
   * set the listener of the sendBtn.
   * 1.get the nick name ,if it is null,set is as "android".
   * 2.send the message to the server.
   */
  sendBtn.setOnClickListener(new OnClickListener(){
   public void onClick(View v) {  
    if(out != null){
     String nickName = null;
     if(nickNameText.getText().toString().split(":").length == 2){
      nickName = nickNameText.getText().toString().split(":")[1];
     }else{
      nickName = "android";
     }
     Log.e("test conntetion", "test send data button");
     out.println(nickName+":"+inputMessage.getText().toString());
     out.flush();
    }
     inputMessage.setText("");
    
   }
  });
  /**
   * run the thread to access the handler to get data from server,and append it to the main frame.
   */
  Thread t = new Thread(this);
  t.start();
}
  public void run(){  
   while(true){
    try {
     if(br != null){  
     data = new String(br.readLine());
     Log.e("get message", data);
     messageHandler.sendEmptyMessage(0);
     }
    } catch (UnsupportedEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  }
/**
   * when messageHandler.sendEmptyMessage(0); runs,the handler will call the call
   * back fucntion handleMessage to append the data from the server.
   */
   private Handler messageHandler = new Handler() {
          @Override
          public void handleMessage(Message msg) {    
           messageContentText.append(data);
           messageContentText.append("\n");
          }
      };
}

嗯,坚持完善的英文注释!!!---这就是我的代码风格。
哦 忘记了 android客户端的界面:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<EditText
android:id="@+id/message_content"
android:layout_width="319px"
android:layout_height="268px"
android:textSize="18sp"
android:layout_x="0px"
android:layout_y="82px"
>
</EditText>
<EditText
android:id="@+id/message_input"
android:layout_width="233px"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_x="10px"
android:layout_y="362px"
>
</EditText>
<Button
android:id="@+id/sendBtn"
android:layout_width="77px"
android:layout_height="wrap_content"
android:text="send"
android:layout_x="240px"
android:layout_y="362px"
>
</Button>

<Button
android:id="@+id/save_message"
android:layout_width="120px"
android:layout_height="40px"
android:text="save message"
android:layout_x="0px"
android:layout_y="40px"
>
</Button>

 

</AbsoluteLayout>


嗯。。。droiddraw-r1b8这个东东真的是个ui好帮手。。有它在可以拖拽控件了  真爽。。你也想要?   5块钱。。。

不说废话,睡觉!


继续,睡到9点半,整个脑都是离个聊天器的新需求:
加一个输入框,设置连接ip和nick name。。




然后当按下connect的时候要有一个进度条显示连接中:



最后就到达聊天框啦:



输入框都是一个activity,connect操作只是将ip同nick name这些参数传到下一个activity处理。socket的链接过程仍然放在ChatForm中进行连接。
嗯。。又一个阶段。。。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics