简体   繁体   中英

Java : incompatible types; int cannot be converted to string

Im just trying to send an integer from my server to my client via sockets.

public static DataOutputStream toClient = null;
public static int clients = 0;

public static void main(String args[]) throws IOException {

        ServerSocket serverSocket = new ServerSocket(1039);
        System.out.println("Server is running..");

        while (true) {
            Socket connsock = null;
            try {
                // accepting client socket
                connsock = serverSocket.accept();

                toClient = new DataOutputStream(connsock.getOutputStream());
                
                System.out.println("A new client is connected : " + connsock);

                clients = clients + 1;
                toClient.writeUTF(clients); //here, I get the incompatible types; int cannot be converted to string
            }
        }
    }
}

I get:

incompatible types; int cannot be converted to string

on the line with toClient.writeUTF(clients); .

what is wrong?

The method writeUTF of DataOutputStream is expecting a String while you provided an int .

When you want to send an int , I would consider the following two options:

  • continue to use writeUTF() , but then you have to convert clients to an int using String.valueOf(clients) .
  • use writeInt instead to send a plain int instead of a String .

Summary:

// convert to String
toClient.writeUTF(String.valueOf(clients));
// send a single plain int value
toClient.writeInt(clients);

That is because writeUTF in DataOutputStream doesnt have an overloaded method which accepts int. So you will need to convert your int to String : Integer.toString(i)

The writeUTF method takes string arguments but your clients variable in your code is an integer type.

Here's the signature:

public final void writeUTF(String str) throws IOException {
    writeUTF(str, this);
}
toClient.writeUTF(clients);

这里 writeUTF(String str) 采用字符串类型参数,因此您必须将客户端整数更改为字符串类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM