客户端:
MainActivity .java
package com.example.socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText editText0;
Button button0;
OutputStream os;
ListView listView0;
List list;
Myadapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText0 = (EditText) findViewById(R.id.in_0);
button0 = (Button) findViewById(R.id.ok_0);
listView0 = (ListView) findViewById(R.id.listview);
list = new ArrayList();
adapter = new Myadapter();
listView0.setAdapter(adapter);
connSocket();
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
// 添加数据到list
list.add(editText0.getText().toString() + "a");
// 刷新适配器
adapter.notifyDataSetChanged();
os.write(editText0.getText().toString().getBytes("utf-8"));
// 强制刷新数据
os.flush();
} catch (Exception e) {
}
editText0.setText(null);
}
});
}
private void connSocket() {
new Thread() {
public void run() {
try {
Socket socke = new Socket("192.168.0.111", 23456);
// 获取输出流
os = socke.getOutputStream();
InputStream in = socke.getInputStream();
// 读取服务器的数据
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
String str = new String(b, 0, len, "utf-8");
list.add(str + "b");
handler.sendEmptyMessage(0x123);
Log.e("TAG", str);
// Message message = new Message();
// Bundle bundle = new Bundle();
// bundle.putString("mess", str);
// handler.sendMessage(message);
}
os.write(editText0.getText().toString().getBytes("utf-8"));
// 强制刷新数据
os.flush();
} catch (Exception e) {
}
};
}.start();
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Bundle bundle = msg.getData();
// String mString = bundle.getString("mess");
// list.add(mString);
if (msg.what == 0x123) {
adapter.notifyDataSetChanged();
}
};
};
class Myadapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
convertView = LayoutInflater.from(MainActivity.this).inflate(
R.layout.item, null);
TextView textView0 = (TextView) convertView
.findViewById(R.id.text0);
TextView textView1 = (TextView) convertView
.findViewById(R.id.text1);
if ("b".equals(list.get(position).toString()
.substring(list.get(position).toString().length() - 1))) {
String b = list.get(position).toString();
textView0.setText(b.substring(0, b.indexOf("b")));
textView1.setVisibility(View.GONE);
} else {
String a = list.get(position).toString();
textView1.setText(a.substring(0, a.indexOf("a")));
textView0.setVisibility(View.GONE);
}
return convertView;
}
}
}
layout:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@null"
android:scrollbars="none" >
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal"
android:paddingLeft="15dp"
android:paddingRight="15dp" >
<EditText
android:id="@+id/in_0"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/edittext_bg"
android:paddingLeft="10dp" />
<Button
android:id="@+id/ok_0"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:text="发送" />
</LinearLayout>
</LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp" >
<TextView
android:id="@+id/text0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="11"
android:textSize="17sp" />
<TextView
android:id="@+id/text1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="11"
android:textColor="#7f00"
android:textSize="17sp" />
</LinearLayout>
</LinearLayout>
服务端:
Chat .java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
public class Chat extends Thread {
private Socket socket;
private OutputStream os;
public Chat(Socket socket) {
// TODO Auto-generated constructor stub
this.socket = socket;
}
@Override
public void run() {
try {
InputStream in = socket.getInputStream();
int len;
byte[] b = new byte[1024 * 5];
while ((len = in.read(b)) != -1) {
String mess = new String(b, 0, len, "utf-8");
// 收到消息发送给客户端
Manager.getManager().ShMess(mess, this);
System.out.print(socket.getLocalAddress() + "发送的消息");
System.err.println(mess);
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 向手机端发送消息
public void out(String mess) {
try {
os = socket.getOutputStream();
os.write(mess.getBytes("utf-8"));
os.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Manager.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Vector;
public class Manager {
// 单例模式
private Manager() {
}
private static Manager ma = new Manager();
// 用于存放Socket对象,线程安全,默认增长一倍
private static Vector<Chat> sockets = new Vector<Chat>();
// static供外部调用添加socket对象
public static void add(Chat chat) {
// 向Vector中添加socket对象
sockets.add(chat);
}
// 返回当前对象
public static Manager getManager() {
return ma;
}
// 发送数据给所有的客户端
public void ShMess(String mess, Chat ch) {
for (int i = 0; i < sockets.size(); i++) {
// 获取客户端对象
Chat chat = sockets.get(i);
if (!chat.equals(ch)) {
// 发送消息
chat.out(mess);
}
}
}
}
QQ_Socket.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class QQ_Socket {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(23456);
System.out.println("服务端已启动");
while (true) {
// 阻塞当前线程一直等待客户端的连接
Socket socket = serverSocket.accept();
Chat chat = new Chat(socket);
chat.start();
// 将对象添加到Vector
Manager.getManager().add(chat);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}