草庐IT

Java TCP连接

coder 2023-09-19 原文

您好,我有一个用 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);
}

所有内容都写在注释行中,为什么 stackoverflow 说添加更多详细信息:D...

/**
 * <h1>Communicate</h1>
 * <p>A reader and sender with client, first it reads imei, then sends back 01.
 * It receives data, as soon it receives it sends back number of records.
 * The while loop initializes and runs until it get interrupted or client disconnects.</p>
 * */
private void Communicate()  {

    imei =  Objects.requireNonNull(ReadInput()).substring(4);
    imei = converter.ReadImei(imei);
    String path = System.getProperty("user.home") + "/Desktop";
    logger = new Logger(path+"/Logs/TCPLogs/"+imei);
    logger.PrintToLOG(GetTime()+" IMEI: " +imei);
    if(imei.length() < 15){
        SendOutput("00");
    }
    else{
        SendOutput("01");
        logger.PrintToLOG("\tResponse: [0" + 1 + "]");
        String input = ReadInput();
        Log(Objects.requireNonNull(input));
        while(flag){
            String recordsCount = GetNumberOfRecords(input);
            SendOutput("000000" + recordsCount);
            logger.PrintToLOG("\tCrc: " + Integer.toHexString(CRC(input)));
            logger.PrintToLOG("\tResponse: [000000" + recordsCount + "]\n");
            input = ReadInput();
            Log(Objects.requireNonNull(input));
        }
    }


/**
 * <h1>Send Output</h1>
 * <p>Sends output to the client</p>
 * @param message the parameter is a received hex data
 * */
private void SendOutput(String message)  {
    try {
        outputStream.write(converter.StringToByteArray(message));
        outputStream.flush();
    } catch (IOException e) {
        System.out.println("Output stream was interrupted");
    }
}








/**
 * <h1>CRC</h1>
 * <p>Calculates CRC of received data</p>
 * @param str the parameter is a received hex data
 * @return int of crc16
 * */
private int CRC(String str) {
    str = str.substring(16, str.length() - 8);
    byte[] bytes = converter.StringToByteArray(str);
    return crc16.getCRC(bytes);
}












/**
 * <h1>Read Input</h1>
 * <p>Reads the input from client. Currently maximum message byte is set up to 8192,
 * if message is bigger then message will not be properly readable and displayed.</p>
 * @return String of received data
 * */
private String ReadInput() {
    byte[] messageByte = new byte[8192];
    int dataSize;
    try {
        dataSize = inputStream.read(messageByte);
        String finalInput = converter.BytesArrayToHex(messageByte, dataSize);
        SendToConsole(finalInput);
        return finalInput;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}














/**
 * <h1>Send To Console</h1>
 * <p>Simply prints out the results to the text area for user</p>
 * @param input the parameter is String format to print in text area
 * */
private void SendToConsole(String input) {
    if(imei!=null)
    {
        String message = viewModel.getClientMessage() + "\r\nFrom imei - "+imei+" : " + input + "\n" + repeatChar();
        Platform.runLater(() -> viewModel.setClientMessage(message));
    }
    else {
        String message = viewModel.getClientMessage() + "\r\nReceived imei - : " + input + "\n" + repeatChar();
        Platform.runLater(() -> viewModel.setClientMessage(message));
    }
}        









/**
 * <h1>Log</h1>
 * <p>Given String is being written to log file.</p>
 * @param data the parameter is a received data
 * */
private void Log(String data) {
    logger.PrintToLOG("\tcodec             : " + data.substring(16, 18));
    logger.PrintToLOG("\tNumber of Records : " + GetNumberOfRecords(data));
    logger.PrintToLOG("\tAVL data          : " + data + "\n");
}

/**
 * <h1>Set Running</h1>
 * <p>Sets flag to run or stop while loop in order to interrupt the thread.</p>
 * */
void setRunning() {
    this.flag = false;
}

/**
 * <h1>Repeat Char</h1>
 * <p>Repeats the '=' character multiple times.</p>
 * @return String is being returned.
 * */
private String repeatChar() {
    char[] data = new char[50];
    Arrays.fill(data, '=');
    return new String(data);
}

/**
 * <h1>Get Time</h1>
 * <p>Gets time when method is being called</p>
 * @return Time in String format
 * */
private String GetTime()
{
    LocalDateTime localDateTime = LocalDateTime.now();
    LocalTime localTime = localDateTime.toLocalTime();
    return localTime.toString();
}


}

public class TCPServer implements Runnable {
private int port;
private Socket socket;
private ServerSocket ss;
private boolean running = true;
private ArrayList<TCPConnection> tcpConnections;

/**
 * <h1>TCP server construct</h1>
 * <p>The tcp server takes port parameter </p>
 * @param port is required for server to listen all incoming connections
 * */
public TCPServer(int port) {
    this.port = port;
}

/**
 * <h1>Run</h1>
 * <p>Runs the runnable thread to listen connections, it accepts a connection, if accept was successful,
 * the connection is added to tcpConnections list and runs the TCPConnection for further listening.
 * The server is running in while loop and stops when Running is set to false,
 * then break is called and shutdowns every connected client.</p>
 * */




public void run() {
    tcpConnections = new ArrayList<>();
    try {
        ss = new ServerSocket(port);
        System.out.println("Listening on port : " + ss.getLocalPort());
        ExecutorService executorService;
        while (true) {
            executorService = Executors.newSingleThreadExecutor();
            socket = ss.accept();
            TCPConnection connection = new TCPConnection(socket);
            executorService.submit(connection);
            tcpConnections.add(connection);
            if (!running) {
                StopConnections();
                break;
            }
        }
        executorService.shutdownNow();
        Thread.sleep(100);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } catch (IOException e) {
        System.out.println("socket is closed");
    }
}

/**
 * <h1>Set Flag</h1>
 * <p>Function is being called when we want to interrupt server thread and stop it.</p>
 * @param flag the parameter sets whenever to true(run server) or false(stop server)
 * */
public void setFlag(boolean flag) {
    running = flag;
    if (!running) {
        try {
            ss.close();
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            System.out.println("Socket is " + socket.isClosed());
        }
    }
}

/**
 * <h1>Stop Connections</h1>
 * <p>Function is being called when we are stopping server,
 * this function iterates through every connection and stops it.</p>
 * */
private void StopConnections() {
    if (!tcpConnections.isEmpty()) {
        for (TCPConnection connections : tcpConnections) {
            connections.setRunning();
        }
        tcpConnections.clear();
    }
}
}

最佳答案

只要您的 android API 级别支持您正在使用的 Java 版本,Android 就支持 Java 代码。您应该没有任何理由不能在 Android 中使用它。

请注意,如果您在 UI 线程上运行任何网络任务,Android 将抛出异常。例如。创建套接字应作为 IntentService 或 AsyncTask 运行,还有其他选项。

关于Java TCP连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52640580/

有关Java TCP连接的更多相关文章

  1. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  2. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  3. ruby - 我的 Ruby IRC 机器人没有连接到 IRC 服务器。我究竟做错了什么? - 2

    require"socket"server="irc.rizon.net"port="6667"nick="RubyIRCBot"channel="#0x40"s=TCPSocket.open(server,port)s.print("USERTesting",0)s.print("NICK#{nick}",0)s.print("JOIN#{channel}",0)这个IRC机器人没有连接到IRC服务器,我做错了什么? 最佳答案 失败并显示此消息::irc.shakeababy.net461*USER:Notenoughparame

  4. ruby-on-rails - 连接字符串时如何在 <%=%> block 内输出 html_safe? - 2

    考虑一下:现在这些情况:#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2#output:http://domain.com/?foo=1&bar=2我需要用其他字符串输出URL。我如何保证&符号不会被转义?由于我无法控制的原因,我无法发送&。求助!把我的头发拉到这里:\编辑:为了澄清,我实际上有一个像这样的数组:@images=[{:id=>"fooid",:url=>"http://

  5. ruby - Faye WebSocket,关闭处理程序被触发后重新连接到套接字 - 2

    我有一个super简单的脚本,它几乎包含了FayeWebSocketGitHub页面上用于处理关闭连接的内容:ws=Faye::WebSocket::Client.new(url,nil,:headers=>headers)ws.on:opendo|event|p[:open]#sendpingcommand#sendtestcommand#ws.send({command:'test'}.to_json)endws.on:messagedo|event|#hereistheentrypointfordatacomingfromtheserver.pJSON.parse(event.d

  6. ruby-on-rails - 什么会导致与 APNS 的连接间歇性断开连接? - 2

    我有一个ruby​​脚本可以打开与Apple推送服务器的连接并发送所有待处理的通知。我看不出任何原因,但当Apple断开我的脚本时,我遇到了管道损坏错误。我已经编写了我的脚本来适应这种情况,但我宁愿只是找出它发生的原因,这样我就可以在第一时间避免它。它不会始终根据特定通知断开连接。它不会以特定的字节传输大小断开连接。一切似乎都是零星的。您可以在单个连接上发送的数据传输或有效负载计数是否有某些限制?看到人们的解决方案始终保持一个连接打开,我认为这不是问题所在。我看到连接在3次通知后断开,我看到它在14次通知后断开。我从未见过它能超过14点。有没有人遇到过这种类型的问题?如何处理?

  7. ruby - 如何断开现有的 ruby​​ 续集与数据库的连接? - 2

    我的意思是之前建立的那个DB=Sequel.sqlite('my_blog.db')或DB=Sequel.connect('postgres://user:password@localhost/my_db')或DB=Sequel.postgres('my_db',:user=>'user',:password=>'password',:host=>'localhost')等等。Sequel::Database类没有名为“disconnect”的公共(public)实例方法,尽管它有一个“connect”。也许有人已经遇到过这个问题。我将不胜感激。 最佳答案

  8. ruby-on-rails - 遗留数据库的 ActiveRecord 连接表 - 2

    我有一个遗留数据库,我正在努力让ActiveRecord使用它。我遇到了连接表的问题。我有以下内容:classTvShow然后我有一个名为tvshowlinkepisode的表,它有2个字段:idShow、idEpisode所以我有2个表和它们之间的连接(多对多关系),但是连接使用非标准外键。我的第一个想法是创建一个名为TvShowEpisodeLink的模型,但没有主键。我的想法是,由于外键是非标准的,我可以使用set_foreign_key并进行一些控制。最后,我想说一些类似TvShow.find(:last).episodes或Episode.find(:last).tv_sho

  9. ruby - rails 3.2.2(或 3.2.1)+ Postgresql 9.1.3 + Ubuntu 11.10 连接错误 - 2

    我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat

  10. Ruby:如何将条件插入字符串连接 - 2

    在字符串连接中,是否可以直接在语句中包含条件?在下面的示例中,我希望仅当dear列表不为空时才连接"mydear"。dear=""string="hello"+"mydear"unlessdear.empty?+",goodmorning!"但是结果报错:undefinedmethod'+'fortrue我知道另一种方法是在这条语句之前定义一个额外的变量,但我想避免这种情况。 最佳答案 使用插值而不是连接更容易和更具可读性:dear=""string="hello#{'mydear'unlessdear.empty?},goodmo

随机推荐