我只是想通过套接字从服务器向客户端发送一个整数。
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
}
}
}
}
我得到:
不兼容的类型; int无法转换为字符串
与toClient.writeUTF(clients);
一行。
怎么了?
答案 0 :(得分:2)
在您提供writeUTF
时,DataOutputStream的方法String
期望有int
。
当您要发送int
时,我会考虑以下两个选项:
writeUTF()
,但是您必须使用clients
将int
转换为String.valueOf(clients)
。writeInt
而不是int
发送普通的String
。摘要:
// convert to String
toClient.writeUTF(String.valueOf(clients));
// send a single plain int value
toClient.writeInt(clients);
答案 1 :(得分:1)
这是因为DataOutputStream中的writeUTF没有接受int的重载方法。因此,您需要将int转换为String:Integer.toString(i)
答案 2 :(得分:0)
writeUTF
方法使用字符串参数,但是代码中的clients
变量是整数类型。
这是签名:
public final void writeUTF(String str) throws IOException {
writeUTF(str, this);
}
答案 3 :(得分:0)
toClient.writeUTF(clients);
在这里writeUTF(String str)具有字符串类型参数,因此您必须将客户端整数更改为字符串类型。