在Android中使用Socket进行长连接,并且不用换行就可以接收数据
private class ServerRunnable implements Runnable {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(18696);
showToast("服务器在端口上启动 18696");
while (!Thread.currentThread().isInterrupted()) {
try {
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int bytesRead;
byte[] data = new byte[1024];
while ((bytesRead = inputStream.read(data)) != -1) {
buffer.write(data, 0, bytesRead);
String received = buffer.toString("UTF-8");
showToast("Received: " + received);//接收到的数据
outputStream.write(("Echo: " + received).getBytes("UTF-8"));//接收到数据之后返回客户端一条数据
outputStream.flush();
buffer.reset();
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void showToast(String message) {
new android.os.Handler(getMainLooper()).post(() ->
Toast.makeText(ServiceGo.this, message, Toast.LENGTH_LONG).show()
);
}
记得初始化
@Override
public void onCreate() {
super.onCreate();
Thread serverThread = new Thread(new ServerRunnable());
serverThread.start();
}
最后在销毁方法中销毁serverThread 、serverSocket