一、服务器端建立Socket监听
1、Class类里添加PORT定义
//add by cbl 3-9 Socket global variable
private static final int PORT = 20001;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService mExecutorService = null; //thread pool
2、创建监听线程
//监听线程
class LooperThread extends Thread {
public void run() {
Looper.prepare();
startSocket();
Looper.loop();
}
}
public void startSocket() {
try {
server = new ServerSocket(PORT);
mExecutorService = Executors.newCachedThreadPool(); //create a thread pool
// Log.v("SoftKeyboard____startSocket", "server start ...");
Socket client = null;
while(true) {
client = server.accept();
mList.add(client);
mExecutorService.execute(new Service(client)); //start a new thread to handle the connection
}
}catch (Exception e) {
e.printStackTrace();
}
}
//接收线程
class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msg = "user" +this.socket.getInetAddress() + "come toal:"
+mList.size();
this.sendmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true) {
if((msg = in.readLine())!= null) {
if(msg.equals("cblexit")) {
//收到"cblexit"字符后,关闭socket
mList.remove(socket);
in.close();
msg = "user:" + socket.getInetAddress()
+ "exit total:" + mList.size();
socket.close();
返回给client:退出提示消息
this.sendmsg();
break;
} else {
//返回给client:IP+server收到的消息
msg = socket.getInetAddress() + ":" + msg;
this.sendmsg();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendmsg() {
System.out.println(msg);
int num =mList.size();
for (int index = 0; index < num; index ++) {
Socket mSocket = mList.get(index);
PrintWriter pout = null;
try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream())),true);
pout.println(msg);
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
3、开启线程实现监听,放在OnCreate函数中,或其他需要启动监听的入口
//add by cbl 3-9 开启线程实现监听
new LooperThread().start();
二、客户端实现TCP Socket发送
1、定义PORT和HOST
private static final String HOST = "127.0.0.1";//"192.168.19.63";
private static final int PORT = 20001;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
2、发送TCP 数据
//send button:TCP client Send
btn_send.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String msg = ed_msg.getText().toString();
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
}
}
}
});
//start button --建立和Socker Server 的连接
btn_start.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//以前用2.2 访问WebService没有问题,到3.0上访问出现android.os.NetworkOnMainThreadException
//找了资料经过实践,解决方法是在activity类中的onCreate方法中添加strict代码,如下:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // or
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
try {
Log.v("client_new Socket", ".................new Socket(HOST, PORT)........");
socket = new Socket(HOST, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.v("client_after new Socket", "...............in out finished........");
} catch (IOException ex) {
ex.printStackTrace();
ShowDialog("login exception" + ex.getMessage());
}
new Thread(SocketDemo.this).start();
}
});
}
public void ShowDialog(String msg) {
new AlertDialog.Builder(this).setTitle("notification").setMessage(msg)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {
if ((content = in.readLine()) != null) {
content += "\n";
mHandler.sendMessage(mHandler.obtainMessage());
} else {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv_msg.setText(tv_msg.getText().toString() + content);
}
};
Manifest.xml 添加网络授权
<uses-permission android:name="android.permission.INTERNET"/>
http://gu6866.iteye.com/blog/1290358