我在我的客戶端有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