簡體   English   中英

如何通過Java中的套接字傳輸整數或字節數組

[英]How to transfer integer or byte array through socket in java

是的,我確實看過有關sun的教程,但在我的情況下它們沒有幫助,只是傳遞了第一個命令。

我有辦法

public void openConnection() throws IOException{

    serverSocket = new ServerSocket(5346);

    Socket simSocket = serverSocket.accept();

    is = simSocket.getInputStream();
    os = simSocket.getOutputStream();

    writer = new PrintWriter(os);
    isReader = new InputStreamReader(is);
    reader = new BufferedReader(isReader);

    System.out.println("Connection succesfull.");
}

public void sendTo(int command) {
    try {
        writer.println(command);
        writer.flush();
    } catch(Exception e) {
        System.out.println("Error sending command to the robot");
        System.out.println(e.toString());
    }
}

在發送方,並且

public static void setUpConnection() {
    try {
        socket = new Socket(InetAddress.getLocalHost(), 5346);
        is = new InputStreamReader(
                socket.getInputStream());
        reader = new BufferedReader(is);
        writer = new PrintWriter(socket.getOutputStream());
        System.out.println("Simulator: connection succesful");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

while (true) {
                intCommand = reader.read();
                ett = reader.readLine(); // does nothing, but without this line it doesn't work
                command = (char) intCommand;

在接收方。 它可以完美地發送一個字符或一個字符的ASCII碼。 我需要更改此代碼以發送整數或僅發送字節數組而不是char。 如果我只留下InputStream和OutputStream,它確實會收到第一個命令,也就是它,而這些方法不斷接收通過sendTo發送的內容。 即使在套接字文檔中,它們也僅具有僅發送字符的示例。

只需對服務器進行編碼,即可將接收到的值存儲為int而不是char。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM