双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

[菜鸟提问]Socket

小小龙虾 CSDN会员 小小龙虾 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
自己在新开的线程创建了个SOCKET
然后又开了个线程接收数据
为什么只有偶然的情况才能收到server端发送的数据呢
请大虾们帮检查检查是不是哪里写的有问题


public SocketConnect(Context context) {
init(context);
new Thread(runnableSocket).start();
new Thread(runnableBlock, "TCP_Recv").start();
}


Runnable runnableSocket = new Runnable() {
@Override
public void run() {
try {
Log.v(TAG, "Start new Socket");
tcpSocket = new Socket(serverIp, SEVER_PORT);
Log.v(TAG, "Socket create success");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};

/** 接收数据 **/
private Runnable runnableBlock = new Runnable() {
@Override
public void run() {
while (isRun) {
if (tcpSocket == null) {
return;
}
receivePacket();
}
}
};

/** 接收数据包 **/
private void receivePacket() {
if (tcpSocket == null)
return;
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
tcpSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String txt = null;
try {
txt = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (txt != null)
Log.v(TAG, "txt = " + txt);
}
...全文
评论 3
收藏 已收藏
分享
返回顶部
小小龙虾 CSDN会员
Android 80,489 成员 91,375 内容