android開發一個聊天室client

來源:互聯網
上載者:User

package com.xgl.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
//import java.net.InetAddress;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ChatRoomActivity extends Activity {
 
    /** Called when the activity is first created. */
 private final String DEBUG_TAG = "ChatRoomActivity";
 //private static final String SERVERIP = "192.168.1.4";
 private static final int SERVERPORT = 54321;
 private Thread mThread = null;
 private Socket mSocket = null;
 private Button mButton_In = null;
 private Button mButton_send = null;
 private EditText mEditText01 = null;
 private EditText mEditText02 = null;
 private BufferedReader mBufferedReader = null;
 private PrintWriter mPrintWriter = null;
 private String mStrMSG = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mButton_In = (Button) findViewById(R.id.Button_In);
        mButton_send = (Button) findViewById(R.id.Button_send);
        mEditText01 = (EditText) findViewById(R.id.editText1);
        mEditText02 = (EditText) findViewById(R.id.editText2);
        // 登陸
 System.out.println("============2===========");
        mButton_In.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    //

    // TODO Auto-generated method stub
    try {
     //InetAddress serverAddr = InetAddress.getByName("192.168.1.234");
//System.out.println(serverAddr.getHostAddress()+"===========Ip============");
     //串連伺服器
     mSocket = new Socket("192.168.1.7",54321);
System.out.println("串連伺服器成功!");
     mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream()));
     mPrintWriter = new PrintWriter(mSocket.getOutputStream(),true);
    } catch (Exception e) {
     e.printStackTrace();
      ShowDialog("登陸異常:" + e.getMessage());
      System.out.println(e.toString()+"====");
     Log.e(DEBUG_TAG, e.toString()+"++++++++");
     // TODO: handle exception
    }
   }
  });
       
       
        mButton_send.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    System.out.println("=======3================");
    // TODO Auto-generated method stub
    try{
     //取得邊框中輸入的資訊
     String str = mEditText02.getText().toString()+"\n";
     //發送給伺服器
     mPrintWriter.print(str);
     mPrintWriter.flush();
    }catch(Exception e){
     //e.printStackTrace();
     Log.e(DEBUG_TAG, e.toString()+"--------");
    }
   }
  });
        mThread = new Thread();
        mThread.start();
    }/*
    private Runnable mRunnable = new Runnable(){
     public void run (){
      while(true){
       try {
     if((mStrMSG = mBufferedReader.readLine()) != null){
      //小心換行
      mStrMSG +="\n";
      mHandler.sendMessage(mHandler.obtainMessage());
     }
    } catch (Exception e) {
     // TODO: handle exception
     Log.e(DEBUG_TAG, e.toString());
    }
      }
     }
    };
    Handler  mHandler = new Handler(){
     public void handleMessage(Message msg){
      super.handleMessage(msg);
      //重新整理
      try {
    mEditText01.append(mStrMSG);
   } catch (Exception e) {
    e.printStackTrace();
    Log.e(DEBUG_TAG,e.toString());
    // TODO: handle exception
   }
     }
    };*/
    public void ShowDialog(String msg) { 
            new AlertDialog.Builder(this).setTitle("提示").setMessage(msg) 
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() { 

      
                        public void onClick(DialogInterface dialog, int which) { 

                           // TODO Auto-generated method stub 
      
                       } 
     
                     }).show(); 
         } 

}

 

 

 

 

 

 

 

 

 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       
        android:text="@string/hello" android:maxLines="10"/>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" android:lineSpacingExtra="12px" android:singleLine="false">

        <requestFocus />
 </EditText>
    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" android:hint="@string/input"/>

    <Button
        android:id="@+id/Button_In"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登陸" />

    <Button
        android:id="@+id/Button_send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="發送"/>

</LinearLayout>

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

chatmainfest.xml別忘了加這句話

<uses-permission android:name="android.permission.INTERNET"/>

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, ChatRoomActivity!</string>
    <string name="app_name">ChatRoom</string>
    <string name="input">你想說點什嗎?</string>

</resources>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.