Android Socket网络通信
2010-07-15 20:10:00 来源:WEB开发网+ mList.size();
this.sendmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if ((msg = in.readLine()) != null) {
if (msg.equals("exit")) {
System.out.println("sssssssssss");
mList.remove(socket);
in.close();
msg = "user:" + socket.getInetAddress()
+ " exit total:" + mList.size();
socket.close();
this.sendmsg();
break;
} else {
msg = socket.getInetAddress() + " : " + msg;
this.sendmsg();
}
}
}
} catch (Exception ex) {
System.out.println("server 读取数据异常");
ex.printStackTrace();
}
}
/**
* 发送消息给所有客户端
*/
public void sendmsg() {
System.out.println(msg);
int num = mList.size();
for (int i = 0; i < num; i++) {
Socket mSocket = mList.get(i);
PrintWriter pout = null;
try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream())),
true);
pout.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2.客户端程序:
Java代码
package com.Aina.Android;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
赞助商链接