我在我的客户端有2个按钮,每个按钮都有一个监听器。如何通过套接字发送字符串和整数?
在我的firt按钮监听器中,我发送了一个字符串在套接字上,并且在spanwed后我得到一个整数数组。那里没问题。这是我的代码。
public void rollDice() {
try {
DataOutputStream sout1 = new DataOutputStream(socket.getOutputStream());
String line = "dice";
PrintStream out1 = new PrintStream(sout1);
out1.println(line);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
随着第二收听我要不要发出首先串把服务器到正确的状态,之后我想送一个整数进程继续进行。这是我的代码,但它似乎不工作。服务器正在打印一个随机数,即使我发送一个“2”。
public void sendDice() {
try {
DataOutputStream sout2 = new DataOutputStream(socket.getOutputStream());
String line = "pick";
PrintStream out2 = new PrintStream(sout2);
out2.println(line);
out2.write(diceListLength);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
这是服务器端。
public void run() {
boolean running = true;
try {
// Create streams for reading/writing lines of text to the socket
DataInputStream input = new DataInputStream(s.getInputStream());
DataInputStream inputInt = new DataInputStream(s.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(s.getOutputStream());
// Print a message:
System.out.println("\nClient from: " + s.getInetAddress() + " port " + s.getPort());
while(running) {
String st = input.readLine();
if (st.equals("dice")) {
for (int i = 0; i < diceRolled.length - number; i++) {
diceRolled[i] = (int) (1 + Math.random() * 6);
System.out.print(diceRolled[i] + " ");
}
output.writeObject(diceRolled);
output.reset();
} else if (st.equals("pick")) {
number = inputInt.readInt();
System.out.print(number);
}
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
// Always be sure to close the socket
} finally {
try {
if (s != null) {
System.out.println(s.getLocalSocketAddress() + " closed.");
s.close();
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
服务器端的'SocketInputStream'在哪里? – Nullpointer
@Nullpointer我正在使用'DataInputStream',但我没有粘贴所有的代码。更新。 – TheNerdFromYesterday
尝试打印'st'..的值是否正确? – Nullpointer