Android Socket网络通信
2010-07-15 20:10:00 来源:WEB开发网public Service(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
msg = "user:" + this.socket.getInetAddress() + " come total:"
+ 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();
}
}
}
}
}
package com;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
更多精彩
赞助商链接