Reputation: 23
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?
Upvotes: 2
Views: 2298
Reputation: 155
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);
}
Upvotes: 0
Reputation: 2863
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:
writeUTF()
, but then you have to convert clients
to an int
using String.valueOf(clients)
.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);
Upvotes: 3
Reputation: 141
toClient.writeUTF(clients);
Here writeUTF(String str) takes string type parameter so you have to change clients integer to string type.
Upvotes: 0
Reputation: 56
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)
Upvotes: 1