您好,我有一个用 Java 编写的代码,我需要在 android studio 中创建一个与 GPS 设备的 TCP 连接,您可以在其中输入 IP/PORT 地址,如果有人可以帮助我,请提前致谢。
public class TCPConnection implements Runnable {
/**
* <h1>TCP Connection construct</h1>
* <p>The tcp connection requires two parameters socket and view model. </p>
* @param socket to establish connection.
* */
TCPConnection(Socket socket) {
super();
this.socket = socket;
converter = new Converter();
crc16 = new Crc16();
}
/**
* <h1>Run function to start listener</h1>
* <p>Simply runs the runnable thread to listen everything from client</p>
* */
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
Listen();
} catch (IOException e) {
e.printStackTrace();
}
}
可能我需要创建一个按钮来开始监听传入连接,也使用 Log 类.....
/**
* <h1>Listen</h1>
* <p>Function for listening connected client</p>
* @throws IOException throws exception if input stream is interrupted
* */
private void Listen() throws IOException {
while (flag) {
System.out.println("listening...");
while (!socket.isClosed() && inputStream.available() == 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
Communicate();
}
inputStream.close();
outputStream.close();
socket.close();
}
/**
* <h1>Get Number Of Records</h1>
* <p>Reads the number of records to send back to the sender</p>
* @param data the parameter is a received hex data
* @return String format number of records
* */
private String GetNumberOfRecords(String data) {
return data.substring(18, 20);
}
侃侃尔雅
相关分类