1、监听某个端口
public class ReceiveCardInfoTask extends AsyncTask<String, Void, Void> {
private static final int RECEIVE_PORT = 8421;
ServerSocket serverSocket = null;
private static Socket socket = null;
@Override
protected Void doInBackground(String... strings) {
try {
serverSocket = new ServerSocket(RECEIVE_PORT);
while (true) {
//循环监听获取数据
socket = serverSocket.accept();
if (socket != null) {
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String str = result.toString(StandardCharsets.UTF_8.name());
Message msg = new Message();
msg.obj = str;
msg.what = 2;
MainActivity.handler.sendMessage(msg);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
启动监听任务:
ReceiveCardInfoTask receiveCardInfoTask = new ReceiveCardInfoTask();
receiveCardInfoTask.execute();
2、发送数据到对应的ip和端口
/**
* 通过socket发送数据到TV上
*
* @param ip:ip地址
* @param port:端口号
* @param passBean:发送的信息类
*/
public static void sendCardInfo(final String ip, final int port, final UploadPassedlogObject passBean) {
new Thread(new Runnable() {
@Override
public void run() {
Socket socket = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("person_type", passBean.getPerson_type());
jsonObject.put("person_id", passBean.getPerson_id());
jsonObject.put("person_name", passBean.getPerson_name());
jsonObject.put("passed_time", passBean.getPassed_time());
jsonObject.put("direction", passBean.getDirection());
jsonObject.put("way", passBean.getWay());
jsonObject.put("site_photo", passBean.getSite_photo());
jsonObject.put("up_from", passBean.getUp_from());
OutputStream outputStream;
socket = new Socket(ip, port);
socket.setSoTimeout(3000);
outputStream = socket.getOutputStream();
outputStream.write(jsonObject.toString().getBytes("utf8"));
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
如果对您有用的话赞一下呗!或者评论66!也好啊!谢谢谢谢~
本文介绍了Android中如何实现Socket通信,包括启动监听任务来接收数据以及如何向指定IP和端口发送数据。通过实例代码详细阐述了相关步骤。


被折叠的 条评论
为什么被折叠?



