请问一下android socket用TCP方式,client端如何监听服务器发送来的数据?
我客户端的发送部分线程的代码如下:
Runnable SendThread = new Runnable() {
public void run() {
try {
//创建一个Socket对象,指定服务器端的IP地址和端口号
socket = new Socket("192.168.0.101",iPort);
//从Socket当中得到OutputStream
OutputStream outputStream = socket.getOutputStream();
byte buffer [] = new byte[1024];
outputStream.write(buffer, 0, 1);
Log.v(MainServerActivity.sTAG,"outputstream flush...");
outputStream.flush();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v(sTAG,"socket is new occur exception...");
e.printStackTrace();
}
}
};
服务器端收到clent的请求接收部分的代码如下:
ServerSocket serverSocket = null;
try {
//创建一个ServerSocket对象,并让这个Socket在4567端口监听
serverSocket = new ServerSocket(MainServerActivity.iPort);
while (!MainServerActivity.bStartShare) {
//调用ServerSocket的accept()方法,接受客户端所发送的请求
Socket socket = serverSocket.accept();
//从Socket当中得到InputStream对象
InputStream inputStream = socket.getInputStream();
//证明接收到请求开始下一次抓屏
ScreenShot();
//saveBitmap(mScreenBitmap);
OutputStream out = socket.getOutputStream();
if (mScreenBitmap.compress(Bitmap.CompressFormat.PNG, 70, out)) {
out.flush();
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
Log.v(MainServerActivity.sTAG,"serverSocket close...");
serverSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
那我的client如何去监听到服务器发给我的数据?请大家帮帮忙。
------解决方案--------------------
client不用监听,当连接建立后client直接接收服务器的数据就行了。参考http://bbs.csdn.net/topics/390316680
------解决方案--------------------
在客户端开启一个子线程,run()方法类似下面这样:
public void run() {
while (isRun) {
try {
if ((msg = bufferedReader.readLine()) != null) {
……
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
在主线程中设置isRun的值,以便在适当的时候停止线程。
------解决方案--------------------
bufferedReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));