聊天室的实现比较粗糙,只有一个ip和一个端口,也就是说所有连接到该服务器的用户都进入一个群组,并未实现创建多个群的功能,我也在考虑多个群的部分。
源码是从别人处copy过来的,大概来源的博客比较旧了,完全还原整个项目之后并不能成功运行。
后来发现在Android4.0之后,就不允许在主线程里调用有关网络的任务了,具体为什么可以自己查询详细了解。我把需要用到网络的部分写到了AsyncTask这个类中,就可以运行了,用了一个晚上才调好,也是够弱的。
感觉AsyncTask蛮好用的,还没有完全了解这个类,不过对于实现粗略的聊天室项目已经够用了。
config.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="初始化設置"
android:textSize="@dimen/h2"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="服務器IP"
android:textSize="@dimen/h3"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="192.168.2.214"
android:id="@+id/ip"
android:textSize="@dimen/et1"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="端口"
android:textSize="@dimen/h3"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="8888"
android:id="@+id/port"
android:textSize="@dimen/et1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="下一步"
android:id="@+id/next"
android:textSize="@dimen/btn1"/>
</LinearLayout>
IniActivity.java
package com.example.socketchat;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class IniActivity extends Activity{
private EditText ip,port;
private Button nextButton;
private String getip,getport;
private ProgressDialog progressDialog;
private InetSocketAddress isa = null;
private SQLiteDatabase db;
private String ipstring=null,portString=null;
private int row=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
ip = (EditText)findViewById(R.id.ip);
port = (EditText)findViewById(R.id.port);
nextButton = (Button)findViewById(R.id.next);
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
try {
Cursor cursor = db.query("config", new String[]{"ip","port"},null,null, null, null, null);
while(cursor.moveToNext()){
ipstring = cursor.getString(cursor.getColumnIndex("ip"));
portString = cursor.getString(cursor.getColumnIndex("port"));
row++;
}
ip.setText(ipstring);
port.setText(portString);
cursor.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
db.close();
nextButton.setOnClickListener(new nextButtonListenner());
}
class nextButtonListenner implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
getip = ip.getText().toString().trim();
getport = port.getText().toString().trim();
if(getip=="" || getip==null || getip.equals("")){
Toast.makeText(IniActivity.this, "請輸入IP", Toast.LENGTH_SHORT).show();
ip.setFocusable(true);
}else if(getport=="" || getport==null || getport.equals("")){
Toast.makeText(IniActivity.this, "請輸入端口", Toast.LENGTH_SHORT).show();
port.setFocusable(true);
}else{
Connect connect = new Connect();
Log.i("connect", connect.toString());
connect.execute();
//progressDialog = ProgressDialog.show(IniActivity.this, "", "請稍後...", true, false);
//new Thread() {
//@Override
//public void run() {
//progressDialog.dismiss();
//finish();
//}
//}.start();
}
}
}
private class Connect extends AsyncTask<Bundle, Integer, Integer>{
@Override
protected Integer doInBackground(Bundle... arg0) {
try {
Socket s = new Socket();
isa = new InetSocketAddress(getip,Integer.parseInt(getport));
Log.i("isa", isa.toString());
s.connect(isa,5000);
//showDialog("連接成功",IniActivity.this);
try {
Log.i("intent0", "intent0");
//生成ContentValues对象
ContentValues values = new ContentValues();
//想该对象当中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据库当中的数据类型一致
values.put("ip", getip);
values.put("port",getport);
Log.i("intent1", "intent1");
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
Log.i("intent0", "intent0");
if(row==0){
db.insert("config", null, values);
Log.i("intent2", "intent2");
}else{
db.update("config", values ,null,null);
Log.i("intent3", "intent3");
}
Log.i("config", "111111");
//Toast.makeText(IniActivity.this, "連接成功", Toast.LENGTH_SHORT).show();
Log.i("intent4", "intent4");
s.close();
Log.i("intent5", "intent5");
Intent intent = new Intent(IniActivity.this,IniuserActivity.class);
Log.i("intent6", "intent6");
startActivity(intent);
IniActivity.this.finish();
db.close();
} catch (Exception e) {
// TODO: handle exception
Log.i("exception", "eeeeee");
//showDialog("設置失敗,數據庫不可用",IniActivity.this);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showDialog("連接失敗,IP或者端口不可用",IniActivity.this);
}catch (SocketTimeoutException e) {
System.out.println("連接超時,服務器未開啟或IP錯誤");
showDialog("連接超時,服務器未開啟或IP錯誤",IniActivity.this);
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
showDialog("連接失敗,IP或者端口不可用",IniActivity.this);
}
return null;
}
}
/**
* define a dialog for show the message
* @param mess
* @param activity
*/
public void showDialog(String mess,Activity activity){
new AlertDialog.Builder(activity).setTitle("信息")
.setMessage(mess)
.setNegativeButton("確定",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
configuser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="初始化設置"
android:textSize="@dimen/h2"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="您的稱呢"
android:textSize="@dimen/h3"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="潤仔"
android:id="@+id/name"
android:maxLength="20"
android:textSize="@dimen/et1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="完成"
android:id="@+id/ok"
android:textSize="@dimen/btn1"/>
</LinearLayout>
IniuserActivity.java
package com.example.socketchat;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class IniuserActivity extends Activity{
private EditText name;
private Button ok;
private SQLiteDatabase db;
private String nameString;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.configuser);
name = (EditText)findViewById(R.id.name);
ok = (Button)findViewById(R.id.ok);
ok.setOnClickListener(new okButtonListenner());
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
try {
Cursor cursor = db.query("config", new String[]{"name"},null,null, null, null, null);
while(cursor.moveToNext()){
nameString = cursor.getString(cursor.getColumnIndex("name"));
}
name.setText(nameString);
cursor.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
db.close();
}
class okButtonListenner implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getname = name.getText().toString().trim();
if(getname==""){
Toast.makeText(IniuserActivity.this, "請輸入您的稱呢", Toast.LENGTH_SHORT).show();
name.setFocusable(true);
}else{
try {
//生成ContentValues对象
ContentValues values = new ContentValues();
//想该对象当中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据库当中的数据类型一致
values.put("name", getname);
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
db.update("config",values,null,null);
Toast.makeText(IniuserActivity.this, "設置完成", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(IniuserActivity.this,SocketmsgActivity.class);
startActivity(intent);
IniuserActivity.this.finish();
db.close();
} catch (Exception e) {
// TODO: handle exception
showDialog("設置失敗,數據庫不可用",IniuserActivity.this);
}
}
}
}
/**
* define a dialog for show the message
* @param mess
* @param activity
*/
public void showDialog(String mess,Activity activity){
new AlertDialog.Builder(activity).setTitle("信息")
.setMessage(mess)
.setNegativeButton("確定",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:id="@+id/chatbox" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_weight="1">
</EditText>
<EditText android:id="@+id/chattxt" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:gravity="top"
android:hint="你想和对方说点什么?">
</EditText>
<Button android:id="@+id/chatOk" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Send"
android:textSize="@dimen/btn1">
</Button>
</LinearLayout>
SocketmsgActivity.java
package com.example.socketchat;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SocketmsgActivity extends Activity {
/** Called when the activity is first created. */
private SQLiteDatabase db;
Thread thread = null;
Socket s = null;
private InetSocketAddress isa = null;
DataInputStream dis = null;
DataOutputStream dos = null;
private String reMsg=null;
private Boolean isContect = false;
private EditText chattxt;
private EditText chatbox;
private Button chatok;
private String chatKey="SLEEKNETGEOCK4stsjeS";
private String name=null,ip=null,port=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
chattxt = (EditText)findViewById(R.id.chattxt);
chatbox = (EditText)findViewById(R.id.chatbox);
chatok = (Button)findViewById(R.id.chatOk);
chatbox.setCursorVisible(false);
chatbox.setFocusable(false);
chatbox.setFocusableInTouchMode(false);
chatbox.setGravity(2);
//初始化,创建数据库来储存用户信息
InitDatabase();
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
try {
Cursor cursor = db.query("config", new String[]{"ip","name","port"},null,null, null, null, null);
while(cursor.moveToNext()){
name = cursor.getString(cursor.getColumnIndex("name"));
ip = cursor.getString(cursor.getColumnIndex("ip"));
port = cursor.getString(cursor.getColumnIndex("port"));
}
cursor.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.toString());
}
db.close();
//设置连接
if(ip==null || port==null){
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
}
//设置名称
else if(name==null){
Intent intent = new Intent(SocketmsgActivity.this,IniuserActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
}else{
Connect connect = new Connect();
connect.execute();
chatok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = chattxt.getText().toString().trim();
System.out.println(s);
try {
dos.writeUTF(chatKey+"name:"+name+"end;"+str);
chattxt.setText("");
}catch (SocketTimeoutException e) {
System.out.println("連接超時,服務器未開啟或IP錯誤");
Toast.makeText(SocketmsgActivity.this, "連接超時,服務器未開啟或IP錯誤", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("連接超時,服務器未開啟或IP錯誤");
Toast.makeText(SocketmsgActivity.this, "連接超時,服務器未開啟或IP錯誤", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
e.printStackTrace();
}
}
});
}
}
private Runnable doThread = new Runnable() {
public void run() {
System.out.println("running!");
ReceiveMsg();
}
};
private class Connect extends AsyncTask<Bundle, Integer, Integer> {
@Override
protected Integer doInBackground(Bundle... arg0) {
try {
s = new Socket();
isa = new InetSocketAddress(ip,Integer.parseInt(port));
s.connect(isa,5000);
if(s.isConnected()){
dos = new DataOutputStream (s.getOutputStream());
dis = new DataInputStream (s.getInputStream());
dos.writeUTF(chatKey+"online:"+name);
/**
* 这里是关键,我在此耗时8h+
* 原因是 子线程不能直接更新UI
* 为此,我们需要通过Handler物件,通知主线程Ui Thread来更新界面。
*
*/
thread = new Thread(null, doThread, "Message");
thread.start();
System.out.println("connect");
isContect=true;
}
}catch (UnknownHostException e) {
System.out.println("連接失敗");
Toast.makeText(SocketmsgActivity.this, "連接失敗", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
e.printStackTrace();
}catch (SocketTimeoutException e) {
System.out.println("連接超時,服務器未開啟或IP錯誤");
Toast.makeText(SocketmsgActivity.this, "連接超時,服務器未開啟或IP錯誤", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
e.printStackTrace();
}catch (IOException e) {
System.out.println("連接失敗");
e.printStackTrace();
}
return null;
}
}
public void disConnect() {
if(dos!=null){
try {
dos.writeUTF(chatKey+"offline:"+name);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 线程监视Server信息
*/
private void ReceiveMsg() {
if (isContect) {
try {
while ((reMsg = dis.readUTF()) != null) {
System.out.println(reMsg);
if (reMsg != null) {
try {
Message msgMessage = new Message();
msgMessage.what = 0x1981;
handler.sendMessage(msgMessage);
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (SocketException e) {
// TODO: handle exception
System.out.println("exit!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 通过handler更新UI
*/
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x1981:
chatbox.setText(chatbox.getText() + reMsg + '\n');
chatbox.setSelection(chatbox.length());
break;
}
}
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
disConnect();
//System.exit(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
menu.add(0, 1, 1, "初始化設置");
menu.add(0, 2, 2, "退出");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId()==1){
Intent intent = new Intent(SocketmsgActivity.this,IniActivity.class);
startActivity(intent);
SocketmsgActivity.this.finish();
}else if(item.getItemId()==2){
disConnect();
SocketmsgActivity.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
return super.onOptionsItemSelected(item);
}
public void InitDatabase(){
if(!config.path.exists()){
config.path.mkdirs();
Log.i("LogDemo", "mkdir");
}
if(!config.f.exists()){
try{
config.f.createNewFile();
Log.i("LogDemo", "create a new database file");
}catch(IOException e){
Log.i("LogDemo",e.toString());
}
}
try {
if(tabIsExist("config")==false){
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
db.execSQL("create table config(_id integer primary key autoincrement," +
"ip varchar(128),port varchar(10),name varchar(32))");
Log.i("LogDemo", "create a database");
db.close();
}
} catch (Exception e) {
// TODO: handle exception
Log.i("LogDemo",e.toString());
}
}
/**
* check the database is already exist
* @param tabName
* @return
*/
public boolean tabIsExist(String tabName){
boolean result = false;
if(tabName == null){
return false;
}
Cursor cursor = null;
db = SQLiteDatabase.openOrCreateDatabase(config.f, null);
try {
String sql = "select count(*) as c from sqlite_master where type ='table' " +
"and name ='"+tabName.trim()+"' ";
cursor = db.rawQuery(sql, null);
if(cursor.moveToNext()){
int count = cursor.getInt(0);
if(count>0){
result = true;
}
}
} catch (Exception e) {
// TODO: handle exception
}
cursor.close();
db.close();
return result;
}
}<strong style="text-decoration: underline; font-style: italic;">
</strong>
config,java
package com.example.socketchat;
import java.io.File;
public class config{
public static String SDCARD = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
public static File path = new File(SDCARD+"/RunChatDatabase/"); //数据库文件目录
public static File f = new File(SDCARD+"/RunChatDatabase/config.db"); //数据库文件
}